我正在用 python 构建一个文本分类器,并且我有每个类的关键短语列表。例如,类别可以是“旅行”和“科学”,列表可以包含:
- 旅行:“纽约”、“韩国”、“首尔”等
- 科学:“科学家”、“化学”等。
我正在寻找在 python 中匹配此类列表中的短语的最佳方法。
例如,文档的结果:
A famous scientist traveled from New York to Seoul, South Korea
应该是: “科学”:1 “旅行”:3
即使字符串的“in”运算符得到了很好的优化,也有一些情况需要处理:
- 单词边界:在某些时候,我可以在字典中包含“to”,并且不想匹配“tomorrow”中的“to”。在这种情况下,标记化可以工作,但短语需要一些自定义逻辑,可能是标记列表中的子列表查找。
- 词干提取:当列表中存在“scientist discovery”时,也应匹配“scientists discovery”
有没有一个Python库可以有效地处理这个问题?如果我需要从头开始实现它,在性能方面处理上述问题的最佳方法是什么?
最佳答案
您试图实现的是词干上的短语搜索。这是文本挖掘 我认为该任务已在搜索引擎中实现。
首先,您需要 tokenize
和 stemmer
函数。标记化可以是
就像这样简单:
def tokenize(string):
return fiter(lambda x: len(x) < 1, remove_punctuation(string).split())
pypi 上有各种词干分析器。
您最终将得到如下所示的函数:
def preprocess(string):
return [stemmer(word) for word in tokenize(string)]
那么您正在寻找的函数如下所示:
from collections import Counter
def count(dictionary, phrase):
counter = Count()
phrase = preprocess(phrase)
for topic, string in dictionary.items():
stems = preprocess(string)
indices = find(phrase, stem[0])
for index in indices:
found = True
for stem in stems[1:]:
if phrase[index + 1] == stem:
continue
else:
found = False
break
if found:
counter[topic] +=1
return counter
字典
变量包含以下信息:
- 旅行:“纽约”、“韩国”、“首尔”等
- 科学:“科学家”、“化学”等。
关于python - 在Python中使用短语和词干进行快速词典查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47307765/