我试图通过解析一长串文本来查找食谱的标签(关键字)。文本包含配方成分、说明和简短的介绍。
您认为从标签列表中删除常用词的最有效方法是什么?
通过常用词,我的意思是:“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()