2014-02-28 26 views
0

我有一大組網址。有些類似於彼此,即它們代表相似的一組頁面。 例如。python中類似網址的分組列表

http://example.com/product/1/ 
    http://example.com/product/2/ 
    http://example.com/product/40/ 
    http://example.com/product/33/ 

是類似的。同樣

http://example.com/showitem/apple/ 
    http://example.com/showitem/banana/ 
    http://example.com/showitem/grapes/ 

也類似。所以我需要將它們表示爲http://example.com/product/(Integers)/ 其中(Integers) = 1,2,40,33http://example.com/showitem/(strings)/其中strings = apple,banana,grapes ...等等。

Python中是否有任何內置函數或庫從大型混合URL中找到這些類似的URL?這如何更有效地完成?請建議。提前致謝。

+0

你需要怎麼處理它們? – msvalkon

+0

我需要檢測這些類型的網址列表並將它們從一組不同的網址分組。 – Bishwash

回答

1

使用字符串來存儲URL的第一部分,只是處理的ID,例如:

In [1]: PRODUCT_URL='http://example.com/product/%(id)s/' 

In [2]: _ids = '1 2 40 33'.split() # split string into list of IDs 

In [3]: for id in _ids: 
    ...:  print PRODUCT_URL % {'id':id} 
    ...:  
http://example.com/product/1/ 
http://example.com/product/2/ 
http://example.com/product/40/ 
http://example.com/product/33/ 

聲明print PRODUCT_URL % {'id':id}使用Python string formatting根據傳遞的變量id來格式化產品URL。

UPDATE:

我看你已經改變了你的問題。針對您的問題的解決方案非常針對特定領域,取決於您的數據集。有幾種方法,比其他方法更手動。這樣的一種方法是讓高層級的網址,即檢索域名:

In [7]: _url = 'http://example.com/product/33/' # url we're testing with 

In [8]: ('/').join(_url.split('/')[:3]) # get domain 
Out[8]: 'http://example.com' 

In [9]: ('/').join(_url.split('/')[:4]) # get domain + first URL sub-part 
Out[9]: 'http://example.com/product' 

[:3][:4]以上只是切片從split('/')

產生的列表,您可以設置結果作爲關鍵在dict上,您每次遇到URL部分時都要記錄一次。然後從那裏繼續。解決方案再次取決於您的數據。如果它變得比上面更復雜,那麼我建議你看看其他答案所暗示的正則表達式。

+0

該解決方案假設我們已經知道類似的網址。但這種情況並非如此。我有很長的網址列表,需要自動檢測類似的網址 – Bishwash

+0

@ user2789099更新了我的答案以迴應您更新的問題 –

0

我不完全確定你正在尋找什麼。我覺得你正在尋找一些與URL匹配的東西。如果這確實是你想要的,那麼我建議你使用使用正則表達式構建的東西。一個例子可以發現here

我還建議你看看Django及其routing system