2013-05-08 70 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