私信  •  关注

Marius Mucenicu

Marius Mucenicu 最近创建的主题
Marius Mucenicu 最近回复了
7 年前
回复了 Marius Mucenicu 创建的主题 » python3.6如何从.txt中正则化URL?

你不需要正则表达式 re 对于这样一个简单的任务。

如果字符串的形式为: 'URL=http://example.net'

然后可以使用基本的python以多种方式解决这个问题,其中之一是:


file_line = 'URL=http://example.net'
start_position = file_line.find('=') + 1  # this gives you the first position after =
end_position = file_line.find('.')

# this extracts from the start_position up to but not including end_position
url = file_line[start_position:end_position]

当然,这只是要提取一个url。假设您使用的是一个大文本,您希望在其中提取所有url,您将希望将此逻辑放入 function 以便您可以重用它,并围绕它进行构建(通过 while 或 for 循环,并且,根据迭代的方式,跟踪最后提取的url的位置等等)。


忠告

这个问题在这个论坛上得到了很多回答,有很多非常熟练的人,例如: here , here , here 和 here ,具体到你会惊讶的程度。这些还不全是,我只是在我的搜索结果中找到了前几个。

考虑到(在发布这个问题的时候)你是这个网站的新贡献者,我友好的建议是投入一些精力去寻找这样的答案。这是一项至关重要的技能,在编程界你离不开它。

记住,无论你遇到什么问题 很有可能 在这个论坛上有人已经遇到了,并且得到了一个答案,你只需要找到它。

7 年前
回复了 Marius Mucenicu 创建的主题 » python3.6如何从.txt中正则化URL?
text = """A key feature of effective analytics infrastructure in healthcare is a metadata-driven architecture. In this article, three best practice scenarios are discussed: https://www.healthcatalyst.com/clinical-applications-of-machine-learning-in-healthcare Automating ETL processes so data analysts have more time to listen and help end users , https://www.google.com/, https://www.facebook.com/, https://twitter.com
code below catches all urls in text and returns urls in list."""

urls = re.findall('(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+', text)

print(urls)

输出:

[ 
   'https://www.healthcatalyst.com/clinical-applications-of-machine-learning-in-healthcare',
   'https://www.google.com/',
   'https://www.facebook.com/',
   'https://twitter.com'
]