2012-10-09 116 views
0

我是新來的Python,我不確定我應該尋找什麼,但我向你保證我已經完成了我的研究,並且仍然爲這個簡單問題想出了一個相當醜陋的20行代碼塊。我怎樣才能把它分成兩個字符串?

我正在處理一個基於金字塔框架的應用程序的遍歷URL。現在

,該URL可以是這些:(URL =無)

  1. URL = 「」
  2. URL = 「/」
  3. URL = 「/ block_1」
  4. URL =「/block_1 /」
  5. URL = 「/ block_1/block_2」
  6. URL = 「/ block_1/block_2 /」

該網址可以不包含任何內容。在這種情況下,我希望我的函數返回False,None或空列表或元組。 (無所謂。)(匹配選項0或1)

Block_1:這是一個單詞,一個到Z的字符串。不能也不應該包含任何特殊字符。實際上,作爲block_1,提取的內容應該位於字典(或列表)中,如果找不到,應該引發並返回錯誤。如果block_1不存在或找不到,則上述函數應返回False,None或空列表或元組。 (匹配選項2和3)

Block_2:Block_2可以是任何東西。爲了簡單起見,它可以包含任何語言的任何字符以及特殊字符,如:()[]。對不起,如果我錯了,但我想我想要的基本上是匹配[\pL\pN].*,但有一個例外:它的最後一個字符不能是任一斜線:既不是"\"也不是"/"。最好是我想它是a to Z (including all languages' alphabets and their accented characters) along with some other characters from a list(我特別定義如上所述:()和[])。如果沒有給出block_2,它應該有None值,如果它不匹配,它應該返回False。 (匹配最後2個選項上面列出)

我的代碼開頭,而原始地對我表示歉意:

if not url: 
    return False 
# then goes on evaluating the first charachter to see if it's a/
if fetch[0] == '/': 
    length = len(url) 
    #then checks if there's a second/for the block_2 
    slash_2 = fetch.find('/', 3) # or '/', 1 
    if slash_2 == -1: 
     block_1, block_2 = url[1:length].lower(), None 
     # checks if block_1 is in a dictionary 
     if not block_1 in the_dict: 
      return False 
    else: # if it's there it processes what's remaining 
     block_1 = fetch[1:slash_2] 
     block_2 = fetch[slash_2+1:] 
     # then checks if there's another slash at the end of block_2 
     if block_2[-1] == '/': # if so it removes it 
      block_2 = block_2[:-1] 
return False # otherwise returns false, which can be() or [] or None 

對不起,如果我的代碼是可怕的,過於複雜。我只想要一個更優雅更好的方式來做到這一點。

那麼我該怎麼做呢?我應該怎麼做才能擺脫這種卡住的代碼行?

謝謝。

回答

4

split('/')應該一定要使用,這應該有助於您解析URL。

如果這還不夠,urlparse應採用解析

urlparse.urlparse(path) 
In [31]: url = 'http://stackoverflow.com/questions/12809298/how-can-i-separate-this-into-two-strings/12809315#12809315' 

In [32]: urlparse.urlparse(url) 
Out[32]: ParseResult(scheme='http', netloc='stackoverflow.com', path='/questions/12809298/how-can-i-separate-this-into-two-strings/12809315', params='', query='', fragment='12809315') 

In [33]: a = urlparse.urlparse(url) 

In [34]: a.path 
Out[34]: '/questions/12809298/how-can-i-separate-this-into-two-strings/12809315' 

In [35]: a.path.split('/') 
Out[35]: 
['', 
'questions', 
'12809298', 
'how-can-i-separate-this-into-two-strings', 
'12809315'] 
2

我想嘗試的第一件事是.split() string function

>>> url = "/block_1/block_2" 
>>> url.split("/") 
['', 'block_1', 'block_2'] 

這將返回一個列表字符串的組成部分,由/字符分隔。從那裏,您可以使用len()函數來查找列表的長度,並根據您所需的邏輯採取適當的操作。

+0

是的,除了一些例外,這是您需要的全部。 – eLRuLL

相關問題