2011-03-23 71 views
0

我不能確定什麼樣的用戶會進入,但我想打破他們的輸入句子分成單詞列表中的如何獲取用戶句子並從中創建單詞列表?

User_input = raw_input("Please enter a search criterion: ") 
User_Input_list[""] 

# input example: steve at the office 

# compiling the regular expression: 
keyword = re.compile(r"\b[aA-zZ]\b") 
    for word in User_input: 
     User_Input_list.append(word?) 

# going by thin put example input I'd want 
# User_Input_list["steve", "at" , "the" , "office"] 

我不確定如何了拆分輸入單獨的詞?我會給餅乾幫忙!

回答

2
User_Input_list = User_input.split() 
+0

這個工作是否會帶來整體感? – RY4N 2011-03-23 10:00:52

+0

它可以處理任何類型的字符串並在空白字符上分割,就像字符串中的單詞一樣。 – poke 2011-03-23 10:07:07

+0

@Ryan這將適用於任何字符串,以及來自@oleide和其他人的解決方案。 oleide的解決方案和我的解決方案之間的區別在於,我的解決方案分裂在任何空白區域,而他的解決方案只分裂在''(空間)角色上。這兩種方法都可以用於不同的情況。 – theheadofabroom 2011-03-23 10:51:50

0

Basicaly,

你應該這樣做:

User_Input_list = User_input.split(' ') 

,就是這樣......

+0

這個工作是否能夠完成? – RY4N 2011-03-23 10:06:41

0

執行以下操作

User_input = raw_input("Please enter a search criterion: ") 

User_Input_list = User_input.split()

0

您發現重已,有分割字符串的一個很好的例子:

re.split('\W+', 'Words, words, words.') 

這樣你得到的所有的話,所有的標點刪除。

1

最簡單的解決辦法可能是使用split

>>> "steve at the office".split() 
['steve', 'at', 'the', 'office'] 

但這不會刪除標點,這可能是也可能不是你一個問題:

>>> "steve at the office.".split() 
['steve', 'at', 'the', 'office.'] 

你可以使用re.split()只拔出字母:

>>> re.split('\W+', 'steve at the office.') 
['steve', 'at', 'the', 'office', ''] 

但正如你可以s EE以上,你可能最終與空條目來處理,和糟糕的是,當你有更微妙的標點符號:

>>> re.split("\W+", "steve isn't at the office.") 
['steve', 'isn', 't', 'at', 'the', 'office', ''] 

所以,你可以在這裏做一些工作,以選擇一個更好的正則表達式,但你需要決定如何處理文字,如steve isn't at the 'the office'

所以要爲你選擇正確的解決方案,你必須考慮你會得到什麼輸入和你想要的輸出。

相關問題