Python:检查关键字是否出现在字符串中

标签 python python-3.x regex pandas

我有两个数据框 - 一个包含自由流动的文本描述,另一个是主词典。我想,以检查是否在任何格式文本描述发生在主字典的话 - 例如,如果主关键字是 123456789 ,它可以存在于用户的文本作为 12345 6789 123 456 789 。关键字可以是数字也可以是字母数字。
我试图删除文本描述中的空格并使用 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

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

最佳答案

您可以使用我的 previous solution 的 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
请参阅 regex demo 。基本上,它是一个 \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
>>> 

关于Python:检查关键字是否出现在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64116882/

相关文章:

python - 无法在 Mac OSC High Sierra 上安装 Python GDAL

python - 如何使用 powershell 循环遍历文件夹中的文件并在其上运行特定的 python 代码?

python-3.x - 在 python 中使用协程。如何链接两个协程

c# - 如何匹配第一个单词?

python - Pandas - 如何填充相应ID之间的缺失值?

python - 具有 Grouper 速度的 Pandas groupby

python - 我用于查找非法 XML 字符的正则表达式在 Python 中非常慢

python - 如果我在子词典中有特定的唯一值,如何断言?

java - 如何限制EditText输入只允许3位整数或小数

Java 正则表达式匹配器验证