Search code examples
pythonstringsimilarity

Inputting a list of strings Python


I have modified a Python code to create a a simple string similarity.

However, I'm trying to do is a user input, where I want the second user input (words) to contain a list of words so that I can compare between words.

    '''
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

When I entered, it seems to make a string similarity with the whole 'w1' input, with all single characters in 'words' input. All I want is for example

w1 = United Kingdom words = United Kingdom, United Kingdoms, United States, Kingdmo.

Then it does a measure where

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

and so on.

Thanks for your help!


Solution

  • You could use str.split to get a list of words:

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

    help on 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.