python-3.x - 是否有一个模块可以计算 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 可以让你使用数据框。
我有使用Counter
fromcollections
from collections import Counter
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
但是,这就是我卡住的地方。如何在 python 中组织一个看起来像所附图像的表格?
解决方案
要做到这一点,需要考虑一些安静的事情,例如处理标点符号、复数、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
推荐阅读
- git - 是否可以使用来自另一台服务器的格式补丁创建补丁?
- css - 在vue js组件的类中插入字符串
- r - 如何更改 R 中 xyplot 的面板函数中的图形参数
- php - 已经在 PHP 中将变量定义为多维数组?
- android - 访问 network-security-config 中的字符串资源
- swift - 无法将协议的通用关联类型的值转换为预期的参数类型
- java - 带有“*”的 Java 绘图形状
- liferay-7 - 如何读取特定的 language.properties 文件?
- json - Flink Kafka - 自定义类数据始终为空
- angular - 如何使用Angular 2更正显示元素列表中的按钮