【问题标题】:python text template matchingpython文本模板匹配
【发布时间】:2020-10-08 06:49:53
【问题描述】:

我必须将文本与正则表达式模板匹配。 示例如下:

templates = {"x":"welcome {1}, how can I help you","y":"hi {1},here is your concern {2}"}
input_text = "welcome john, how can I help you" # for this output should be "x"
input_text = "Hi john,here is your concern sick leave"# for this output shoud be "y"
input_text = "Welcome john, how can I help you, how are you?" # for this output should be None
input_text = "can I know your name" # for this output should be None

您能否提供一些意见来解决这个问题? 提前致谢。

【问题讨论】:

  • 您提出了一个问题,并且真诚地有人花时间和精力来回答您的问题。你已经接受了他们的回答,所以我认为这对你有帮助。请不要破坏您的问题,因为这对帮助过您的人非常不尊重。

标签: python text nlp


【解决方案1】:

您首先需要将模板转换为有效的正则表达式。在这里,我将{1}{2} 替换为匹配任何非空字符链的正则表达式.+。由于第三个示例也需要完全匹配而不是部分匹配,因此我将 $ 添加到正则表达式以强制它匹配文本直到结束。

regex_temp = re.sub(r'\{\s*\d+\s*\}','.+',template) + '$'

然后您只需遍历模板并测试每个模板。 re.I 标志使其不区分大小写,因为您的示例包含大写和小写文本。

另一种选择是直接将模板调整为有效的正则表达式,如下所示: templates = {"x":"welcome .+, how can I help you$","y":"hi .+,here is your concern .+"} 然后您使用正则表达式中的模板并删除上面的字符串转换。

import regex as re
templates = {"x":"welcome {1}, how can I help you","y":"hi {1},here is your concern {2}"}

def find_template(input_text):
    for template_key, template in templates.items():
       regex_temp = re.sub(r'\{\s*\d+\s*\}','.+',template) + '$'
        if re.match(regex_temp, input_text, flags=re.I):
            return template_key
    return None

input_text = "welcome john, how can I help you" # for this output should be "x"
print(find_template(input_text))
input_text = "Hi john,here is your concern sick leave"# for this output shoud be "y"
print(find_template(input_text))
input_text = "Welcome john, how can I help you, how are you?" # for this output should be None
print(find_template(input_text))
input_text = "can I know your name" # for this output should be None
print(find_template(input_text))

>> x
>> y
>> None
>> None

【讨论】:

  • 感谢您的宝贵意见。这里需要更改而不是regex_temp = template.replace('{1}', '.+').replace('{2}', '.+') + '$,我使用了适合所有参考号的regex_temp = re.sub(r'\{\s*\d+\s*\}','.+',template) + '$'
  • 我根据您的评论调整了答案
猜你喜欢
  • 2013-01-07
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多