20

我试图通过解析一长串文本来查找食谱的标签(关键字)。文本包含配方成分、说明和简短的介绍。

您认为从标签列表中删除常用词的最有效方法是什么?

通过常用词,我的意思是:“the”、“at”、“there”、“their”等。

我有两种可以使用的方法,您认为哪种方法在速度方面更有效,您知道我可以使用哪种更有效的方法吗?

方法 1:
- 确定每个单词出现的次数(使用库 Collections)
- 拥有一个常用词列表,并通过尝试从 Collection 对象中删除该键(如果存在)来从 Collection 对象中删除所有“常用词”。
- 因此速度将由变量 delims 的长度决定

import collections from Counter
delim     = ['there','there\'s','theres','they','they\'re'] 
# the above will end up being a really long list!
word_freq = Counter(recipe_str.lower().split())
for delim in set(delims):
    del word_freq[delim]
return freq.most_common()

方法 2:
- 对于可以是复数的常用词,查看配方字符串中的每个词,并检查它是否部分包含常用词的非复数版本。例如; 对于字符串“There's a test”,检查每个单词是否包含“there”,如果包含则将其删除。

delim         = ['this','at','them'] # words that cant be plural
partial_delim = ['there','they',] # words that could occur in many forms
word_freq     = Counter(recipe_str.lower().split())
for delim in set(delims):
    del word_freq[delim]
# really slow 
for delim in set(partial_delims):
    for word in word_freq:
        if word.find(delim) != -1:
           del word_freq[delim]
return freq.most_common()
4

3 回答 3

33

我会做这样的事情:

from nltk.corpus import stopwords
s=set(stopwords.words('english'))

txt="a long string of text about him and her"
print filter(lambda w: not w in s,txt.split())

哪个打印

['long', 'string', 'text']

如果您认为散列集查找是 O(1),那么复杂度应该是字符串中单词数的 O(n)。

FWIW,我的 NLTK 版本定义了 127 个停用词

'all', 'just', 'being', 'over', 'both', 'through', 'yourselves', 'its', 'before', 'herself', 'had', 'should', 'to', 'only', 'under', 'ours', 'has', 'do', 'them', 'his', 'very', 'they', 'not', 'during', 'now', 'him', 'nor', 'did', 'this', 'she', 'each', 'further', 'where', 'few', 'because', 'doing', 'some', 'are', 'our', 'ourselves', 'out', 'what', 'for', 'while', 'does', 'above', 'between', 't', 'be', 'we', 'who', 'were', 'here', 'hers', 'by', 'on', 'about', 'of', 'against', 's', 'or', 'own', 'into', 'yourself', 'down', 'your', 'from', 'her', 'their', 'there', 'been', 'whom', 'too', 'themselves', 'was', 'until', 'more', 'himself', 'that', 'but', 'don', 'with', 'than', 'those', 'he', 'me', 'myself', 'these', 'up', 'will', 'below', 'can', 'theirs', 'my', 'and', 'then', 'is', 'am', 'it', 'an', 'as', 'itself', 'at', 'have', 'in', 'any', 'if', 'again', 'no', 'when', 'same', 'how', 'other', 'which', 'you', 'after', 'most', 'such', 'why', 'a', 'off', 'i', 'yours', 'so', 'the', 'having', 'once'

显然你可以提供你自己的一套;我同意您对您的问题的评论,即提供您想要预先消除的所有变体可能是最简单(也是最快)的,除非您想消除比这更多的单词,但它变得更像一个问题发现有趣的而不是消除虚假的。

于 2012-04-07T23:45:04.510 回答
13

您的问题域是“自然语言处理”。

如果您不想重新发明轮子,请使用NLTK ,在文档中搜索词干。

鉴于NLP是计算机科学中最难的学科之一,重新发明这个轮子需要大量的工作......

于 2012-03-31T06:38:06.847 回答
1

你问的是速度,但你应该更关心准确性。您的两个建议都会犯很多错误,删除太多或太少(例如,有很多单词包含子字符串“at”)。我赞同研究 nltk 模块的建议。事实上,NLTK 书中的早期示例之一涉及删除常用词,直到最常见的剩余词揭示有关该类型的某些内容。您不仅会获得工具,还会获得有关如何进行操作的说明。

无论如何,您编写程序所花费的时间比计算机执行它所花费的时间要长得多,因此请专注于把它做好。

于 2012-04-07T23:24:27.687 回答