2013-05-08 90 views
1

我修改了一段Python代碼來創建一個簡單的字符串相似度。輸入字符串列表Python

但是,我試圖做的是用戶輸入,我希望第二個用戶輸入(單詞)包含單詞列表,以便我可以比較單詞。

''' 
Input the English words in w1, and 
the translated Malay words in the list 
''' 
w1 = raw_input("Enter the English word: ") 
words = raw_input("Enter all the Malay words: ") 
## The bits im not sure what to code 
wordslist = list(words) 

for w2 in wordslist: 
    print(w1 + ' --- ' + w2) 
    print(string_similarity(w1, w2)) 
    print 

當我進入,這似乎讓與整個「W1」輸入字符串的相似性,在「單詞」輸入所有單個字符。我想要的全是例如

w1 =英國 words =英國,聯合王國,美國,金德莫。

隨後,它的量度,其中

United Kingdom --- United Kingdom 
United Kingdom --- United Kingdoms 
United Kingdom --- United Sates 
United Kingdom --- Kingdmo 

等。

感謝您的幫助!在str.split

>>> strs = "United Kingdom, United Kingdoms, United States, Kingdmo" 
>>> strs.split(",") 
['United Kingdom', ' United Kingdoms', ' United States', ' Kingdmo'] 

幫助

回答

1

你可以使用str.split獲得單詞列表

>>> str.split? 
Namespace: Python builtin 
Docstring: 
S.split([sep [,maxsplit]]) -> list of strings 

Return a list of the words in the string S, using sep as the 
delimiter string. If maxsplit is given, at most maxsplit 
splits are done. If sep is not specified or is None, any 
whitespace string is a separator and empty strings are removed 
from the result. 
+0

對不起,問一個愚蠢的問題,但我怎麼做到這一點用戶輸入?我已經嘗試在我的用戶輸入下使用str.split(「,」),它仍然單獨處理字符串(每個字符)。 謝謝! – bn60 2013-05-08 02:20:55

+0

@ user1433571用戶輸入的單詞必須用逗號分隔(類似於您發佈的問題)。然後使用'words = words.split(「,」)'。 – 2013-05-08 02:25:21

+0

謝謝,這個作品完美!正如我所需要的一樣! :) – bn60 2013-05-08 02:36:05

0

如前所述,像', '.split()會做你的要求。但一個更好的替代用戶可能會逐一輸入,那麼你不必擔心分隔符等:

>>> words = [] 
>>> while True: 
... s = raw_input('Input a Malay word (or enter to continue): ') 
... if s == '': 
...  break 
... else: 
...  words.append(s) 
... 
Input a Malay word (or enter to continue): United kingdom 
Input a Malay word (or enter to continue): United kingdoms 
Input a Malay word (or enter to continue): United States 
Input a Malay word (or enter to continue): Kingdmo 
Input a Malay word (or enter to continue): 
>>> print words 
['United kingdom', 'United kingdoms', 'United States', 'Kingdmo'] 
+0

這個工程就像一個魅力。謝謝! – bn60 2013-05-08 02:23:08

+0

其他答案更符合我的需求,但是謝謝,你的工作也非常棒! – bn60 2013-05-08 02:36:34