首页 > 解决方案 > Python:检查关键字是否在字符串中出现拆分

问题描述

我有两个数据框 - 一个包含自由流动的文本描述,另一个是主词典。我正在尝试检查主词典中的单词是否以任何格式出现在文本描述中 - 例如,如果主关键字是123456789,它可以在用户文本中以12345 6789123 456 789的形式出现。关键字既可以是数字也可以是字母数字。

我试图删除文本描述中的空格并检查使用函数,但这种方法也匹配噪音。例如,它也将匹配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

任何线索都会有所帮助。提前致谢。

标签: pythonpython-3.xregexpandas

解决方案


您可以使用我以前的解决方案的 Pandas 改编版:

import pandas as pd
import numpy as np
import re

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'])

words = master_dict['Keyword'].to_list()
words_dict = { f'g{i}':item for i,item in enumerate(words) } 
rx = re.compile(r"(?i)\b(?:" + '|'.join([ r'(?P<g{}>{})'.format(i,"[\W_]*".join([c for c in item])) for i,item in enumerate(words)]) + r")\b")
print(rx.pattern)

def findvalues(x):
    m = rx.search(x)
    if m:
        return [words_dict.get(key) for key,value in m.groupdict().items() if value][0]
    else:
        return np.nan

df['Match'] = df['Text'].apply(lambda x: findvalues(x))

模式是

(?i)\b(?:(?P<g0>1[\W_]*2[\W_]*3[\W_]*4[\W_]*5[\W_]*6[\W_]*7[\W_]*8)|(?P<g1>a[\W_]*s[\W_]*1[\W_]*2[\W_]*3[\W_]*4[\W_]*5[\W_]*6))\b

请参阅正则表达式演示。基本上,它是一个\b(?:keyword1|keyword2|...|keywordN)\b正则表达式,[\W_]*每个字符之间都有(匹配任何零个或多个非字母数字字符)。由于\b, 单词边界,关键字仅作为整个单词匹配。它适用于您的关键字,因为您确认它们是数字或字母数字。

演示输出:

>>> df
  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       NaN
4  5  sample bas123 456ts text       NaN
>>> 

推荐阅读