Replacing a word in a list with a value from a dict

后端 未结 2 1880
抹茶落季
抹茶落季 2021-01-15 05:59

I\'m trying to create a simple program that lets you enter a sentence which will then be split into individual words, saved as splitline. For example:



        
2条回答
  •  日久生厌
    2021-01-15 06:20

    I'm not sure why you're iterating over every character, assigning splitline to be the same thing every time. Let's not do that.

    words = text.split()  # what's a splitline, anyway?
    

    It looks like your terminology is backwards, dictionaries look like: {key: value} not like {value: key}. In which case:

    my_dict = {'the': 1, 'in': 2, 'a': 3}
    

    is perfect to turn "the man lives in a house" into "1 man lives 2 3 house"

    From there you can use dict.get. I don't recommend str.replace.

    final_string = ' '.join(str(my_dict.get(word, word)) for word in words)
    # join with spaces all the words, using the dictionary substitution if possible
    

    dict.get allows you to specify a default value if the key isn't in the dictionary (rather than raising a KeyError like dict[key]). In this case you're saying "Give me the value at key word, and if it doesn't exist just give me word"

提交回复
热议问题