【问题标题】:python extract URLs from a text file with no html tagspython从没有html标签的文本文件中提取URL
【发布时间】:2018-02-05 09:36:00
【问题描述】:

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

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

regex 使用下面的代码从文本文件中获取 url,但问题是它也需要不必要的字符,例如 '>'

这是我的代码:

import re
def extractURLs(fileContent):
    urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[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>

如您所见,有一些字符(例如“>”)会导致问题。我做错了什么?

【问题讨论】:

  • 你能分享一些emailBody.txt的内容吗?那么帮助你会更容易
  • 很难理解你的文字。所以你能在你的问题中添加这个文本吗?在URLs = URLs + extractURLs(fileContent),你之前没有定义URLs
  • 抱歉打扰了。我知道我的问题与正则表达式有关。请想象其余代码工作正常。

标签: python regex parsing url


【解决方案1】:

快速解决方案,假设 '>' 是唯一出现在末尾的字符:url.rstrip('>')

删除单个字符串的字符的最后一次出现(多个)。因此,您必须遍历列表并删除该字符。

编辑:刚买了一台带有python的PC,所以在测试后给出一个正则表达式答案。

import re
def extractURLs(fileContent):
    urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[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() 会更简单。

【讨论】:

  • “删除单个字符串的最后一次出现的字符”不太正确。如果字符串末尾有多个“>”,rstrip() 会将它们全部删除。但从它的声音来看,这就是 OP 想要的。
  • 是的,你是对的。我将编辑我的答案以使其更加清晰。坚持以简单的方式获得 OP 的需要以获取干净的 url。在您提到的情况下,简单的方法是检查最后一个字符(lastChar = url[len(url) - 1])是否为>,如果是True,则为cleanUrls.append(url[:-1])
  • 获取url最后一个字符最简单的方法是url[-1],无需调用len()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 2021-10-22
  • 2018-07-15
  • 2018-10-16
  • 2021-08-08
  • 2017-04-24
相关资源
最近更新 更多