python - 从字符串中删除常用词(及其复数形式)的技术

标签 python parsing processing-efficiency

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

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

对于常用词,我指的是像“the”、“at”、“there”、“their”等这样的词。

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

方法一:
- 确定每个单词出现的次数(使用库 Collections)
- 拥有一个常用词列表,并通过尝试从集合对象中删除该键(如果存在)从集合对象中删除所有“常用词”。
- 因此速度将由变量 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()

方法二:
- 对于可以是复数的常用词,查看食谱字符串中的每个词,并检查它是否部分包含常用词的非复数版本。例如;对于字符串“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()

最佳答案

我会做这样的事情:

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'

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

关于python - 从字符串中删除常用词(及其复数形式)的技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9953619/

相关文章:

python - Robotframework.request - 如何发出内容为 "multipart/form-data"的 POST 请求

Python mysql看不到数据库中的数据变化

Python:读取海量文件中添加的新信息

php - 如何解析.mp3文件php

css - 将字符串解析为 SASS 中的映射

performance - Perl中拆分超长音译的效率

python - 从 Google Colab 连接到 Postgresql 数据库

python - 使用带有 Unicode 的 Python 正则表达式进行 BackReference

c - 高效的C/C++多线程程序可对数据进行分区和处理

csv - 将大量数据从CSV文件上传到数据库的有效方法?