【问题标题】:Inputting a list of strings Python [duplicate]输入字符串列表Python [重复]
【发布时间】:2013-05-08 01:46:35
【问题描述】:

我已经修改了一个 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' 输入的字符串相似,所有单个字符都在 'words' 输入中。我想要的只是举例

w1 = 英国 words = United Kingdom、United Kingdoms、United States、Kingdmo。

然后它会在哪里进行测量

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

等等。

感谢您的帮助!

【问题讨论】:

    标签: python string similarity


    【解决方案1】:

    您可以使用str.split 获取单词列表:

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

    帮助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.
    

    【讨论】:

    • 很抱歉问了一个愚蠢的问题,但是我如何从用户输入中获得这个?我尝试在我的用户输入下使用 str.split(",") ,它仍然单独处理字符串(每个字符)。谢谢!
    • @user1433571 用户输入的单词必须用逗号分隔(类似于您发布的问题)。然后使用words = words.split(",")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2019-09-01
    • 2022-01-03
    • 2015-04-29
    相关资源
    最近更新 更多