saz*_*azr 16 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()
Run Code Online (Sandbox Code Playgroud)
方法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()
Run Code Online (Sandbox Code Playgroud)
tim*_*day 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())
Run Code Online (Sandbox Code Playgroud)
打印
['long', 'string', 'text']
Run Code Online (Sandbox Code Playgroud)
如果您认为散列集查找为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'
Run Code Online (Sandbox Code Playgroud)
显然你可以提供自己的套装; 我同意你的问题的评论,它可能是最容易(也是最快)提供你想要消除的所有变化,除非你想要消除比这更多的单词但是它变得更像一个问题发现有趣的,而不是消除虚假的.