[英]Lambda remove words from string
一直試圖弄清楚為什么這不起作用:
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
我不認為 lambda function 正在做我預期的事情,再多的調整也無法產生正確的結果。 我試圖只提取“倫敦”這個詞。
有任何想法嗎?
只需將您的 3d 行替換為:
command = command.replace("?", "").split('weather')[1].split() #remove ", " from split
結果將是“倫敦”
原因是因為 your.split(", ") 實際上並沒有拆分文本,而是將其保存為列表中的一個元素(無法在下一個命令中正確連接)
你把它分開了,這是一種有效的方法:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.