从python中的计数器中删除停止字列表

2024-10-02 16:29:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在NLTK中有一个函数来生成一个一致性列表,它看起来像

concordanceList = ["this is a concordance string something", 
               "this is another concordance string blah"] 

我还有另一个函数,它返回一个计数器字典,其中包含concordanceList中每个单词的计数

^{pr2}$

我遇到的问题是如何最好地从结果计数器中删除非索引字,这样,当我调用

mostCommonWords(concordanceList).most_common(10)

结果不仅仅是{“the”:100,“is”:78,“that”:57}。在

我认为预先处理文本以删除非索引词已经过时了,因为我仍然需要协调字符串作为语法语言的实例。基本上,我想问的是,有没有比为非连续字词创建一个停止字词计数器,将值设置为低,然后再制作另一个类似这样的计数器:

stopWordCounter = Counter(the=1, that=1, so=1, and=1)
processedWordCounter = mostCommonWords(concordanceList) & stopWordCounter

它应该将所有stopword的count值设置为1,但这看起来很糟糕。在

编辑:另外,我在实际制作这样一个stopWordCounter时遇到了困难,因为如果我想包括像“and”这样的保留字,我会得到一个无效的语法错误。计数器有易于使用的并集和交集方法,这将使任务相当简单;字典是否有等效的方法?在


Tags: andthe方法函数string字典thatis
3条回答

我会将项目平铺成单词,忽略任何停止词,而是将其作为单个Counter的输入:

from collections import Counter
from itertools import chain

lines = [
    "this is a concordance string something", 
    "this is another concordance string blah"
]

stops = {'this', 'that', 'a', 'is'}    
words = chain.from_iterable(line.split() for line in lines)
count = Counter(word for word in words if word not in stops)

或者,最后一点可以作为:

^{pr2}$

你可以在标记化过程中删除停止词。。。在

stop_words = frozenset(['the', 'a', 'is'])
def mostCommonWords(concordanceList):
    finalCount = Counter()
    for line in concordanceList:
        words = [w for w in line.split(" ") if w not in stop_words]
        finalCount.update(words)  # update final count using the words list
    return finalCount

首先,不需要在函数中创建所有新的Counter;可以执行以下操作:

for line in concordanceList:
    finalCount.update(line.split(" "))

相反。在

其次,Counter是一种字典,因此可以直接删除项目:

^{pr2}$

无论sword是否在Counter中,这都不会引发异常。在

相关问题 更多 >