使用Python将字符串URL拆分为单词

时间:2017-01-30 12:16:49

标签: python url split

如何从python中的字符串(URL)中获取各种单词? 来自以下网址:

http://www.sample.com/level1/level2/index.html?id=1234

我希望得到像这样的词:

http, www, sample, com, level1, level2, index, html, id, 1234

任何使用python的解决方案。

感谢。

2 个答案:

答案 0 :(得分:5)

这是您为所有网址

执行此操作的方法
import re
def getWordsFromURL(url):
    return re.compile(r'[\:/?=\-&]+',re.UNICODE).split(url)

现在您可以将其用作

url = "http://www.sample.com/level1/level2/index.html?id=1234"
words = getWordsFromURL(url)

答案 1 :(得分:1)

根据最大的非孤元序列进行正则表达式分割:

import re
l = re.split(r"\W+","http://www.sample.com/level1/level2/index.html?id=1234")
print(l)

的产率:

['http', 'www', 'sample', 'com', 'level1', 'level2', 'index', 'html', 'id', '1234']

这很简单,但正如有人指出的那样,当URL名称中有_-,...时不起作用。因此,列出可以分离路径部分的所有可能令牌的解决方案就不那么有趣了:

l = re.split(r"[/:\.?=&]+","http://stackoverflow.com/questions/41935748/splitting-a-stri‌​ng-url-into-words-us‌​ing-python")

(我承认我可能忘记了一些分离符号)

相关问题