首页 > 解决方案 > 是否有一个模块可以计算 Python 中字符串列表的出现次数?

问题描述

我已经定义了一个列表,它读取多个文件的内容并存储所有文件。如何创建一个数据框,每个文件名在一行中,并且相应的列计算每个单词的出现并输出它。

举个例子,假设这一切都是明确定义的(但如果需要,我可以提供原始代码):

#define list
words = [ file1_contents, file2_contents ]

file1_contents = "string with dogs, cats and my pet sea turtle that lives in my box with my other turtles."
file2_contents = "another string about my squirrel, box turtle (who lives in the sea), but not my cat or dog".

filter_words = ["cat", "dog", "box turtle", "sea horse"]

输出将是这样的:

output = {'file1'{'cat': 1, 'dog':1, 'box turtle': 1, 'sea horse': 0}, 'file2'{ ...}} 

我附上了我的最终目标的图像。我刚开始使用python,所以我不太确定我会在这里使用什么包/模块?我知道 pandas 可以让你使用数据框。

我有使用Counterfromcollections

from collections import Counter
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

但是,这就是我卡住的地方。如何在 python 中组织一个看起来像所附图像的表格?

示例输出: 在此处输入图像描述

标签: python-3.xpandasnltkcounter

解决方案


要做到这一点,需要考虑一些安静的事情,例如处理标点符号、复数、1 术语 2 术语单词等。

from sklearn.feature_extraction.text import CountVectorizer
from nltk.stem import WordNetLemmatizer
# nltk.download('wordnet')
import string
import pandas as pd

def preproc(x): 

    #make translator object
    trans=str.maketrans('','',string.punctuation)
    wnl = WordNetLemmatizer()

    x = ' '.join([wnl.lemmatize(e) for e in x.translate(trans).split()])
    return x

vectorizer = CountVectorizer(vocabulary=filter_words, 
                             ngram_range=(1,2),
                             preprocessor=preproc)

X = vectorizer.fit_transform(words)

pd.DataFrame(columns=filter_words,
            data=X.todense())

输出:

    cat dog box turtle  sea horse
0   1   1   0           0
1   1   1   1           0

推荐阅读