Search code examples
pythonpython-3.xnlp

Searching string values in a dictionary


I want to change some of the words of my string, S to some others based on the dictionary, D. For example, for the following values of S and D:

S="I don't know, who you are?"
D={"doesn't":"does not","don't":"do not"}

I should get

S="I do not know, who you are?"

To do this, I am writing the following code:

L=str.split(' ')
index = [D[x] if x in D.keys() for x in L]

But this is giving syntax error. Kindly help me in resolving this error so that I am able to get the required output as shown above. If there is an even better solution to this problem, please explain that.


Solution

  • You just need to get the string value if the value is not in the dictionary.

    result = ' '.join(D.get(x,x) for x in S.split(' '))
    

    The reason for syntax error with [D[x] if x in D.keys() for x in L] is that if needs to go after for if there is no accompanying else condition. Look up the syntax in the documentation.