用于命名实体的Python自然语言处理

时间:2012-04-13 06:12:11

标签: python nlp

我正在编写一个python Web应用程序,我需要处理其中包含命名实体的搜索查询。例如, 如果搜索查询是: “mac os lion” 并且假设我必须使用我的数据库中可用的候选人来处理此查询:

  • Google Android。
  • Microsoft Windows。
  • Apple Mac OS X Lion
  • ...

我们都知道第三个结果是正确的结果。但有没有办法我们可以将用户的查询,即“mac os lion”映射到“Apple Mac OS X Lion”(这是我数据库中的可用条目) 有人可以告诉我该寻找什么或做什么。

2 个答案:

答案 0 :(得分:2)

您需要对用户查询进行某种规范化,并且必须“学习”从这些查询到正确“类”的映射。

一种简单的方法是计算匹配任何“类”的“标记”的重叠。以下示例代码可能有所帮助:

CLASSES = ['Google Android', 'Microsoft Windows', 'Apple Mac OS X Lion']

def classify_query(query_string):
    """
    Computes the most "likely" class for the given query string.

    First normalises the query to lower case, then computes the number of
    overlapping tokens for each of the possible classes.

    The class(es) with the highest overlap are returned as a list.

    """
    query_tokens = query_string.lower().split()
    class_tokens = [[x.lower() for x in c.split()] for c in CLASSES]

    overlap = [0] * len(CLASSES)
    for token in query_tokens:
        for index in range(len(CLASSES)):
            if token in class_tokens[index]:
                overlap[index] += 1

    sorted_overlap = [(count, index) for index, count in enumerate(overlap)]
    sorted_overlap.sort()
    sorted_overlap.reverse()

    best_count = sorted_overlap[0][0]

    best_classes = []
    for count, index in sorted_overlap:
        if count == best_count:
            best_classes.append(CLASSES[index])
        else:
            break

    return best_classes

示例输出

classify_query('mac OS x') -> ['Apple Mac OS X Lion']
classify_query('Google') -> ['Google Android']

当然,这只是一个非常基本的解决方案。您可能希望添加一些拼写检查,以便在查询字符串中出现拼写错误时更加健壮...

希望有所帮助:)

答案 1 :(得分:1)

如果您只需要查找与查询类似的文本,则可以使用带有python绑定的文本搜索引擎,例如Lucene + PyLucene