【问题标题】:Read URLs from .txt file Python从 .txt 文件 Python 中读取 URL
【发布时间】:2018-06-10 10:02:32
【问题描述】:

我正在尝试使用正则表达式从 .txt 文件中提取 URL(所有 URL 都以 .jpeg 结尾)。这是我的正则表达式:

import re
output = re.findall('(http)(.*?)(jpeg)', text)

但我的输出如下所示:

('http', ://d1spq65clhrg1f.cloudfront.net/uploads/image_request/image/182/182382/182382534/cloudsight.', 'jpeg')

如何避免用逗号分隔匹配项?

【问题讨论】:

  • 添加样本数据并输出
  • 是否要求您只捕获以“.jpeg”结尾的 URL?或者其他结尾也有效,例如“.jpg”或“.gif”或根本没有扩展名?如果是这样,您能否在问题中更清楚地说明这一点?

标签: python regex url pattern-matching


【解决方案1】:

试试这个

import re
output = re.findall('(http.*?jpeg)', text)

输出:

['http://d1spq65clhrg1f.cloudfront.net/uploads/image_request/image/182/182382/182382534/cloudsight.jpeg']

这将使“re.findall”只捕获一个组 - “http.*?jpeg”,而不是您的正则表达式中的三个。

【讨论】:

  • 即使是一组也不需要。 re.findall(r'http.*?jpeg', text).
  • 你知道我在哪里可以批量下载网址中的图片吗?
  • @StefanoPozzi 我听说过关于搜索引擎的好消息。你不是世界上第一个使用 Python 下载东西的人。
【解决方案2】:

我不确定你是否正在寻找这个

import re
output = " ".join(re.findall('(http)(.*?)(jpeg)', text))

【讨论】:

  • 我收到此错误:“TypeError: sequence item 0: expected str instance, tuple found”
  • 不行,不确定的请不要回答。
  • @MunimMunna ,我不确定 op 是否只想删除逗号并将其作为字符串。然而,适当地指出了一点。欢呼
【解决方案3】:
output = re.findall('https?:.*?.jpeg', text)

例子

import re
text=" asdd adf sdf sf http://d1spq65clhrg1f.cloudfront.net/uploads/image_request/image/182/182382/182382534/cloudsight.jpeg asfd ads f ads asdfadfasf asd asdf asdf asdf as"
output = re.findall('https?:.*?.jpeg', text)
print(output)

输出:

['http://d1spq65clhrg1f.cloudfront.net/uploads/image_request/image/182/182382/182382534/cloudsight.jpeg']

【讨论】:

    【解决方案4】:
    import re 
    
    with open("urls.txt") as f:
        urls = re.findall('(http*.*?jpeg)', f.read())
        print urls
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2018-04-02
      • 2017-10-02
      • 1970-01-01
      相关资源
      最近更新 更多