首页 > 解决方案 > Python 匹配文件中的所有 URL,并在文件中的新行上列出每个 URL

问题描述

我正在尝试获取一个脚本,该脚本可以打开一个文件,匹配所有 URL 的文件并输出一个仅包含匹配项的新文件。以下情况目前发生的只是获得第一场比赛。我正在解析的文件基本上是 1 行带有多个 url “这是一个随机的 url 字符串http://www.yandex.ru:8080http://www.hao123.com:8080,这里还有一点,http ://www.wordpress.com:8080,”

import re

with open("C:\\Users\\username\\Desktop\\test.txt") as f:
    Lines = f.readlines()
file_to_write = open("C:\\Users\\username\\Desktop\\output.txt", "w")
pattern = 'https?:\/\/(?:w{1,3}\.)?[^\s.]+(?:\.[a-z]+)*(?::\d+)?(?![^<]*(?:<\/\w+>|\/?>))'
matches = []
for line in Lines:
   m = re.search(pattern, line)
   if m:
     matches.append(m.group(0))
   print(matches)
   file_to_write.write("\n".join(matches))

现在,如果我将正则表达式替换为更简单的内容,例如 "'(https?://. ):(\d )'" 我会得到所有匹配项,但它们并没有在行上分开,它们都连接在一起线。

不确定如何完全修改脚本或正则表达式以捕获所有 url 的 base:port 并添加到新行。

正则表达式的当前输出 ('(https?://. ):(\d )'):

http://www.yandex.ru:8080, http://www.hao123.com:8080, antoher bit here , http://www.wordpress.com:8080,http://www.gmw.cn:8080, http://www.tumblr.com:8080/test/etete/eete, http://www.paypal.com:8080

期望的输出:

http://www.yandex.ru:8080
http://www.hao123.com:8080
http://www.wordpress.com:8080
http://www.gmw.cn:8080
http://www.tumblr.com:8080
http://www.paypal.com:8080

标签: python-3.xregex

解决方案


您可以尝试re.findall(以及您拥有的模式):

>>> import re
>>>
>>> s = 'This is a a random string of urls http://www.yandex.ru:8080, http://www.hao123.com:8080, another bit here, http://www.wordpress.com:8080,'
>>> pattern = 'https?:\/\/(?:w{1,3}\.)?[^\s.]+(?:\.[a-z]+)*(?::\d+)?(?![^<]*(?:<\/\w+>|\/?>))'
>>> urls = re.findall(pattern, s)
>>> urls
['http://www.yandex.ru:8080', 'http://www.hao123.com:8080', 'http://www.wordpress.com:8080']

然后,您可以使用您认为合适的list名称。urls例如,要将 URL 写入文件中,您可以使用(就像您已经拥有的那样)file_to_write.write('\n'.join(urls))。举例说明:

>>> print('\n'.join(urls))
http://www.yandex.ru:8080
http://www.hao123.com:8080
http://www.wordpress.com:8080

推荐阅读