2017-08-28 118 views
-1

我发现这里的大多数帖子都是靠近标签以在文本文件中找到url。但并非所有的文本文件都必须在它们旁边都有html标签。我正在寻找一种适用于这两种情况的解决方案。以下正则表达式是:python从没有html标签的文本文件中提取URL

'http[s]?://(?:[a-zA-Z]|[0-9]|[[email protected]&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' 

正则表达式来使用以下代码从文本文件中获取的URL,但问题是它也需要不必要的字符,如“>”

这是我的代码:

import re 
def extractURLs(fileContent): 
    urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[[email protected]&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', fileContent.lower()) 
    print urls 
    return urls 

myFile = open("emailBody.txt") 
fileContent = myFile.read() 
URLs = URLs + extractURLs(fileContent) 

输出的例子如下:

http://saiconference.com/ficc2018/submit 
http://52.21.30.170/sendy/unsubscribe/qhiz2s763l892rkps763chacs52ieqkagf8rbueme9n763jv6da/hs1ph7xt5nvdimnwwfioya/qg0qteh7cllbw8j6amo892ca> 
https://www.youtube.com/watch?v=gvwyoqnztpy> 
http://saiconference.com/ficc 
http://saiconference.com/ficc> 
http://saiconference.com/ficc2018/submit> 

正如你可以看到有一些字符acters(如'>')导致问题。我究竟做错了什么?

+0

可以请你分享一下** emailBody.txt **的内容。那么它会更容易地帮助你 – Arijit

+0

>在线提交:http://saiconference.com/FICC2018/Submit >会议网站提供完整的详细信息:http ://saiconference.com/FICC >会议视频 |取消订阅 mazkopolo

+0

这很难理解您的文本。所以你可以在你的问题中添加这个文本,并且在'URLs = URLs + extractURLs(fileContent)'中,你之前没有定义过'URLs' – Arijit

回答

1

快速溶液,假设“>”是出现在最后的唯一字:url.rstrip('>')

删除字符的最后出现的(多个),用于一个字符串。所以,你将不得不遍历整个列表并移除角色。

编辑:刚刚有一台PC与python,所以给测试后的正则表达式的答案。

import re 
def extractURLs(fileContent): 
    urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[[email protected]&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', fileContent.lower()) 
    cleanUrls = [] 
    for url in urls: 
     lastChar = url[-1] # get the last character 
     # if the last character is not (^ - not) an alphabet, or a number, 
     # or a '/' (some websites may have that. you can add your own ones), then enter IF condition 
     if (bool(re.match(r'[^a-zA-Z0-9/]', lastChar))): 
      cleanUrls.append(url[:-1]) # stripping last character, no matter what 
     else: 
      cleanUrls.append(url) # else, simply append to new list 
    print(cleanUrls) 
    return cleanUrls 

URLs = extractURLs("http://saiconference.com/ficc2018/submit>") 

但是,如果它只是一个字符,使用.rstrip()更简单。

+0

“删除单个字符串的最后一次出现的字符”不太正确。如果字符串末尾有多个“>”,则rstrip()将全部删除它们。但通过它的声音,这正是OP想要的。 – PaulMcG

+0

是的,你是对的。我将编辑我的答案,使其更加清晰。坚持OP的需求,以简单的方式获得一个干净的网址。在你提到的情况下,这种简单的方法是检查最后一个字符('lastChar = url [len(url) - 1]')是否是'>',如果是'True',那么'cleanUrls.append( url [: - 1])' – RetardedJoker

+1

获取url最后一个字符的最简单方法是'url [-1]',不需要调用len()。 – PaulMcG