Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用re.findall获取链接_Python - Fatal编程技术网

Python 使用re.findall获取链接

Python 使用re.findall获取链接,python,Python,我正在尝试获取文件中给定的所有链接。所有链接都包含在“”中,有http、https和ftp链接。下面是该文件的输出示例 $ cat file "http://www.google.com" and "http://www.yahoo.com" and "http://www.facebook.com" "https://1.1.1.1" and "ftp://a.a.a.a" 下面是我的python代码 In [109]: FILE = open('file','r') In [110]

我正在尝试获取文件中给定的所有链接。所有链接都包含在“”中,有http、https和ftp链接。下面是该文件的输出示例

$ cat file 

"http://www.google.com" and "http://www.yahoo.com" and "http://www.facebook.com"
"https://1.1.1.1" and "ftp://a.a.a.a"
下面是我的python代码

In [109]: FILE = open('file','r')

In [110]: data = FILE.read()

In [111]: links = re.findall('"((http|ftp)s?://.*?)"', data)

In [112]: print links

    [('http://www.google.com', 'http'), ('http://www.yahoo.com', 'http'), ('http://www.facebook.com', 'http'), ('https://1.1.1.1', 'http'), ('ftp://a.a.a.a', 'ftp')]
为什么输出在原始链接后包含“http”。我哪里出错了?
有人能帮忙吗。我在Python2.7.6中使用(ipython2.3.1),因为您的正则表达式包含两个捕获组。第一个捕获组捕获整个链接,而另一个捕获组仅捕获
http
ftp
部分。我建议您将第二个捕获组改为非捕获组,因为
re.findall
函数优先选择捕获组。如果在正则表达式上找不到捕获组,则只有它返回匹配项

re.findall(r'"((?:http|ftp)s?://.*?)"', data)
示例:

>>> s = '''"http://www.google.com" and "http://www.yahoo.com" and "http://www.facebook.com"
"https://1.1.1.1" and "ftp://a.a.a.a"'''
>>> re.findall(r'"((?:http|ftp)s?://.*?)"', s)
['http://www.google.com', 'http://www.yahoo.com', 'http://www.facebook.com', 'https://1.1.1.1', 'ftp://a.a.a.a']

如果所有文件看起来都像这样,则可以拆分和剥离:

lines=""""http://www.google.com" and "http://www.yahoo.com" and    "http://www.facebook.com"
"https://1.1.1.1" and "ftp://a.a.a.a"""

print([x.strip('"') for x in lines.split(" and ")])

['http://www.google.com', 'http://www.yahoo.com', 'http://www.facebook.com"\n"https://1.1.1.1', 'ftp://a.a.a.a']

可能与捕获组有关。您在
http | ftp
周围加了括号,表示对该子表达式匹配的内容感兴趣,因此也会返回它。但是我不知道python或者使用过的正则表达式模块,所以请恕我直言,文件内容并不完全相同。但是谢谢你的把戏:)