所以我有以下文本示例:
Good Morning,
The link to your exam is https://uni.edu?hash=89234rw89yfw8fw89ef .Please complete it within the stipulated time.
If you have any issue, please contact us
https://www.uni.edu
https://facebook.com/uniedu
我想要的是提取考试链接的url:https://uni.edu?hash=89234rw89yfw8fw89ef。我计划使用findAll((函数,但在编写正则表达式以提取特定url时遇到了困难。
import re
def find_exam_url(text_file):
filename = open(text_file, "r")
new_file = filename.readlines()
word_lst = []
for line in new_file:
exam_url = re.findall('https?://', line) #use regex to extract exam url
return exam_url
if __name__ == "__main__":
print(find_exam_url("mytextfile.txt"))
我得到的输出是:
['http://']
代替:
https://uni.edu?hash=89234rw89yfw8fw89ef
非常感谢在这方面的帮助。
此正则表达式有效:
>>> re.findall('(https?://.*?)s', s)
['https://uni.edu?hash=89234rw89yfw8fw89ef',
'https://www.uni.edu',
'https://facebook.com/uniedu']
其中s
表示文件中的文本(由f.read()
读取(,使用的模式为(https?://.*?)s
(延迟匹配直到出现空白(。
如果你需要提取作为考试链接提到的url,你可以让regex更具体:
>>> re.findall('exam.*(https?://.*?)s', s)
['https://uni.edu?hash=89234rw89yfw8fw89ef']
或者看起来检查链接会有一个?hash=
形式的标识符/URL参数,所以这样的东西更好
>>> re.findall('(https?://.*?hash=.*?)s', s)
['https://uni.edu?hash=89234rw89yfw8fw89ef']