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

2019-02-19 21:47发布

问题:

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:

the man lives in a house

Each word will be matched against a dict that contains a number of words stored against values such as:

mydict = {"the":1,"in":2,"a":3}

If the word is present in the dict, then I want the word to be replaced with the key associated with the value so that the output will look like:

1 man lives 2 3 house

I created some code that allows me to test if each word exists in the dict which was then able to output 'true' or 'false' for every word in the sentence but when I tried to replace the word with the key from the dict I goit a little stuck.

Here's what I tried so far:

text = input("Enter a sentence \n")
    for word in text:
        splitline = text.split(" ")

mydict = {"the":1,"in":2,"a":3}

for word in splitline:
    if word in dict.keys(mydict):

        #I tried to declare x as the value from the dict
        x = str(dict.values(mydict))

        #newline should be the original splitline with word replaced with x
        newline = splitline.replace(word,x)

        #the program should print the newline with word replaced with key
        print(newline)

It seems I can't use splitline.replace with dict.keys(mydict) as I assume that it will select all of the keys and not just the instance I am trying to deal with. Is there a way I can do this?

I hope I've explained myself properly.

回答1:

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"



回答2:

Now that you have your dict the proper way, you can do regular dict object stuff like checking for keys and grabbing values:

>>> text = 'the man lives in a house'
>>> mydict = {"the":1,"in":2,"a":3}
>>> splitlines = text.split()
>>> for word in splitlines:
    if word in mydict:
        text = text.replace(word,str(mydict[word]))

HOWEVER, note that with this:

>>> text
'1 m3n lives 2 3 house'

since a is a key, the a in man will be replaced. You can instead use regex to ensure word boundaries:

>>> text = 'the man lives in a house'
>>> for word in splitlines:
    if word in mydict:
        text = re.sub(r'\b'+word+r'\b',str(mydict[word]),text)


>>> text
'1 man lives 2 3 house'

the \b ensures that there is word boundary around each match.