简体   繁体   中英

Lambda remove words from string

Been trying to get my head around why this is not working:

command = "What's the weather like in London?"
words = ["in", "like"]

command = command.replace("?", "").split('weather')[1].split(", ")
command = ",".join(filter(lambda x: x not in words, command))

print(command)

Output:

 like in London

I don't think the lambda function is doing what I anticipated it would, and no amount of tweaking can yield the correct result. I'm trying to extract only the word 'London'.

Any ideas?

Just replace your 3d line by this:

command = command.replace("?", "").split('weather')[1].split()  #remove ", " from split

Result will be 'London'

The reason is because your.split(", ") doesn't actually split the text but it saves it as one element in a list (which cannot be joined correctly in next command)

You're splitting it wrong, here's an efficient way to do it:

command = "What's the weather like in London?"

command = "".join([x for x in command.replace("?", "").split('weather')[1].split(" ") if x not in ["in", "like"]])

print(command)

output:

London

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM