从字符串中删除常用单词(及其复数版本)的技巧

时间:2012-03-31 06:29:15

标签: python parsing processing-efficiency

我试图通过解析一长串文本来找到食谱的标签(关键字)。该文本包含配方成分,方向和简短的模糊。

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

一般来说,我的意思是:'the','at','there','their'等等。

我有两种我可以使用的方法,您认为哪种方法在速度方面更有效率,您是否知道我能以更有效的方式做到这一点?

方法1:
- 确定每个单词出现的次数(使用库集合)
- 有一个常用单词列表,并通过尝试从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:
- 对于可以是复数的常用单词,查看配方字符串中的每个单词,并检查它是否部分包含常用单词的非复数形式。例如;对于字符串“有一个测试”,检查每个单词以查看它是否包含“那里”并删除它(如果有)。

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()

3 个答案:

答案 0 :(得分:26)

我会做这样的事情:

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 stopwords

'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'
显然你可以提供自己的套装;我同意你的问题的评论,它可能是最简单(也是最快)的,只提供你想要消除的所有变化,除非你想要消除比这更多的单词但是它变得更像一个问题发现有趣的,而不是消除虚假的。

答案 1 :(得分:10)

您的问题域名是" Natural Language Processing"。

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

鉴于NLP是计算机科学中最难的科目之一,重新发明这个轮子是很多工作......

答案 2 :(得分:1)

你问速度,但你应该更关心准确性。你的建议都会犯很多错误,删除太多或太少(例如,很多包含子字符串的单词“at”)。我的第二个建议是查看nltk模块。事实上,the NLTK book中的一个早期例子涉及删除常用词,直到最常见的词仍然揭示关于该流派的某些内容。你不仅可以获得工具,还可以获得如何进行操作的说明。

无论如何,你花费的时间比计算机执行它所花费的时间要长得多,所以要专注于做好它。