我正在编写一个 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/