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

标签 python nlp

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

  • 谷歌安卓。
  • 微软 window 。
  • Apple Mac OS X Lion
  • ...

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

最佳答案

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

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

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

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

希望对您有所帮助:)

关于命名实体的 Python 自然语言处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10136077/

相关文章:

python - 计算包含 None 类型的列表的均值和最小值

python - 绘制图像到 gtk.DrawingArea?

python - 如何使用 bcrypt 将纯文本密码与散列密码进行比较?

python - 简短短语的快速文本表示,但不适用于包含短短语的较长短语

prolog - 普林斯顿 wordnet prolog 文件 - 如何使用 sense key

algorithm - Earley 识别器到 Earley 解析器

python - 有人能告诉我我的 WIP Python 刽子手游戏出了什么问题吗?

python - Pandas:在数据帧的最后一行添加一个具有单个值的新列

java - 我如何使用 LingPipe Tools 提取阿拉伯命名实体

java - 使用wordnet api检查地名、人名或组织名