簡體   English   中英

使用Python將字符串URL拆分為單詞

[英]Splitting a String URL into words Using Python

如何從python中的字符串(URL)中獲得各種單詞? 從如下網址:

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

我想得到這樣的詞:

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

任何使用python的解決方案。

謝謝。

這是您可能會對所有網址執行的操作

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)

只是根據非字母數字的最大序列進行正則表達式拆分:

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")

(我承認我可能已經忘記了一些分隔符號)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM