所以,我有一个熊猫的列名是 笔记 其中包含一个句子或对某些事件的解释。我试图从这一列中找到一些给定的单词,当我找到这个单词时,我将其添加到下一列中,作为 种类
问题是针对一些特定的词,例如 骗子, 谎言 它的取词方式是 熟悉 和 家庭 因为他们都有骗子和谎言在里面。
Notes Type
2 families are living in the address Lies
He is a liar Liar
We are not familiar with this Liar
从上面可以看出只有第二句是正确的。如何才能只捡到骗子、谎言等单独的词,而不捡到家人或熟悉的词。
这是我的方法。
word= ["Lies"]
for i in range(0, len(df)):
for f in word:
if f in df["Notes"][i]:
df["Type"][i] = "Lies"
感谢任何帮助。谅谅
使用 \b
词界 regex
和 .str.extract
来寻找模式。
df.Notes.str.extract(r'\b(lies|liar)\b')
标注那些包含该词的行,做。
df['Type'] = np.where(df.Notes.str.contains(r'\b(lies|liar)\b'), 'Lies', 'Not Lies')
好吧,我同意Quang Hoang的答案。请你一定要注意 "他不是一个骗子 "这样的句子。在那里它仍然会匹配并给你Liar。
我想这段如果代码对你来说是可以的!
import pandas as pd
df = pd.DataFrame.from_dict({"Notes":["2 families are living in the address" ,
"He is a liar " ,
"We are not familiar with this " ] })
word= ["liar","are","this"]
found_in_whole_string =[]
for i in range(0, len(df)):
found_one_word=[]
for f in word:
if f in df["Notes"][i].split(" "):
found_one_word.append(f)
else:
found_one_word.append("")
found_in_whole_string.append(",".join([word for word in found_one_word if len(word) > 0]) )
df["type"] = found_in_whole_string