python-3.x - Python 匹配文件中的所有 URL,并在文件中的新行上列出每个 URL
问题描述
我正在尝试获取一个脚本,该脚本可以打开一个文件,匹配所有 URL 的文件并输出一个仅包含匹配项的新文件。以下情况目前发生的只是获得第一场比赛。我正在解析的文件基本上是 1 行带有多个 url “这是一个随机的 url 字符串http://www.yandex.ru:8080,http://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
解决方案
您可以尝试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
推荐阅读
- ios - 在 CCAvenue iOS 中解密应用程序请求的问题
- unity3d - 在加载场景之前调用 Update()
- python - 在不使用 dask 数据框的情况下获取 dask 数组的唯一行
- java - 自定义列表视图中的空指针异常视图持有者
- c# - 多重绑定,转换器和设置器:意外错误
- azure - 从具有相同用户访问权限的 Azure AD 获取应用程序列表
- reactjs - Typescript 定义中的私有方法(React)
- c# - 如何在我的接收器中获取一些上下文数据
- php - 如何以正确的方式PHP制作回调函数
- python - 从多于一列的 pandas 数据框构建 networkx 有向图或流程图