我有两个数据框 - 一个包含自由文本说明,另一个是主词典。我正在尝试检查主词典中的单词是否以任何格式出现在文本说明中 - 例如,如果主关键字是123456789,它可能出现在用户文本中,如12345 6789或123 456 789。关键字可以是数字也可以是字母数字混合。
我已经尝试从文本说明中删除空格,并使用in函数进行检查,但这种方法还会匹配噪声。例如,它还将匹配b123 4567 89klx。我想仅匹配整个关键字被拆分并作为多个单词给出,而不是在不同单词之间。
我现在的代码:
我已经尝试从文本说明中删除空格,并使用in函数进行检查,但这种方法还会匹配噪声。例如,它还将匹配b123 4567 89klx。我想仅匹配整个关键字被拆分并作为多个单词给出,而不是在不同单词之间。
我现在的代码:
def matcher(x,word_dict):
match=""
for i in list(dict.fromkeys(word_dict)):
if i.replace(" ", "").lower() in x.replace(" ", "").lower():
if(match==""):
match=i
else:
match=match+"_"+i
return match
import pandas as pd
df = pd.DataFrame({'ID' : ['1', '2', '3', '4','5'],
'Text' : ['sample 123 45 678 text','sample as123456 text','sample As123 456','sample bas123456 text','sample bas123 456ts text']},
columns = ['ID','Text'])
master_dict= pd.DataFrame({'Keyword' : ['12345678','as123456']},
columns = ['Keyword'])
df['Match']=df['Text'].apply(lambda x: matcher(x,master_dict.Keyword))
Expected Output
ID Text Match
0 1 sample 123 45 678 text 12345678
1 2 sample as123456 text as123456
2 3 sample As123 456 as123456
3 4 sample bas123456 text NA
4 5 sample bas123 456ts text NA
任何线索都将有助于。提前感谢。
[ ]*
替换[\W_]*
。 - Wiktor Stribiżew