【问题标题】:Python RegEx code to detect specific features in a sentencePython RegEx 代码检测句子中的特定特征
【发布时间】:2019-01-29 02:30:03
【问题描述】:

我创建了一个简单的单词特征检测器。到目前为止,能够找到字符串中的特定特征(混杂在其中),但算法会与某些单词序列混淆。让我举例说明:

from nltk.tokenize import word_tokenize
negative_descriptors = ['no', 'unlikely', 'no evidence of']
negative_descriptors = '|'.join(negative_descriptors)
negative_trailers = ['not present', 'not evident']
negative_trailers = '|'.join(negative_descriptors)

keywords = ['disc prolapse', 'vertebral osteomyelitis', 'collection']

def feature_match(message, keywords, negative_descriptors):
    if re.search(r"("+negative_descriptors+")" + r".*?" + r"("+keywords+")", message): return True
    if re.search(r"("+keywords+")" + r".*?" + r"("+negative_trailers+")", message): return True

以上返回True 用于以下消息:

message = 'There is no evidence of a collection.' 
message = 'A collection is not present.'

这是正确的,因为它暗示我正在寻找的关键字/条件不存在。但是,它会为以下消息返回 None

message = 'There is no evidence of disc prolapse, collection or vertebral osteomyelitis.'
message = 'There is no evidence of disc prolapse/vertebral osteomyelitis/ collection.'

似乎在第一条消息中匹配“或椎骨骨髓炎”,在第二条消息中匹配“/集合”作为否定匹配,但这是错误的,并暗示消息显示“我正在寻找的条件是存在的” '。它实际上应该返回“True”。

如何防止这种情况发生?

【问题讨论】:

    标签: python regex nltk


    【解决方案1】:

    您发布的代码有几个问题:

    1. negative_trailers = '|'.join(negative_descriptors) 应该是 negative_trailers = '|'.join(negative_trailers )
    2. 您还应该像处理其他列表一样将列表关键字转换为字符串,以便将其传递给正则表达式
    3. 在你的正则表达式中使用 3 次 'r' 是没有用的

    经过这些更正后,您的代码应如下所示:

    negative_descriptors = ['no', 'unlikely', 'no evidence of']
    negative_descriptors = '|'.join(negative_descriptors)
    negative_trailers = ['not present', 'not evident']
    negative_trailers = '|'.join(negative_trailers)
    
    keywords = ['disc prolapse', 'vertebral osteomyelitis', 'collection']
    keywords = '|'.join(keywords)
    
    if re.search(r"("+negative_descriptors+").*("+keywords+")", message): neg_desc_present = True
    if re.search(r"("+keywords+").*("+negative_trailers+")", message): neg_desc_present = True
    

    【讨论】:

      猜你喜欢
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 2014-04-04
      • 2017-07-09
      • 1970-01-01
      • 2016-05-19
      • 2016-12-10
      相关资源
      最近更新 更多