我正在用python构建一个文本分类器,并为每个类提供了一个关键短语列表。例如,课程可以是“旅行”和“科学”,清单可以包括:
我正在寻找最好的方法来匹配python中这样的列表中的短语。
例如,文件的结果:
一位著名的科学家从纽约到韩国首尔
应该是:“科学”:1“旅行”:3
即使字符串的"in“运算符得到了很好的优化,也有几种情况需要处理:
是否有一个可有效处理此问题的python库?如果我需要从头开始实现它,在性能方面处理上述问题的最佳方法是什么?
发布于 2018-01-14 10:55:47
你想要实现的是词组搜索。我认为这是一项文本挖掘任务,并在搜索引擎中实现。
首先,您需要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 counterdictionary变量包含以下信息:
发布于 2017-11-15 12:54:06
在这种情况下,一个简单的解决方案是使用字典理解:
s = "A famous scientist traveled from New York to Seoul, South Korea"
d = {"travel":["New York", "South Korea", "Seoul"], "science": ["scientist", "chemical"]}
final_results = {a:sum(i in s for i in b) for a, b in d.items()}输出:
{'science': 1, 'travel': 3}https://stackoverflow.com/questions/47307765
复制相似问题