【发布时间】:2020-03-18 13:11:02
【问题描述】:
我正在尝试创建一个从数据框中获取特定单词频率的函数。我正在使用 Pandas 将 CSV 文件转换为数据框,并使用 NLTK 对文本进行标记。我能够获得整列的计数,但我很难获得每一行的频率。以下是我到目前为止所做的。
import nltk
import pandas as pd
from nltk.tokenize import word_tokenize
from collections import defaultdict
words = [
"robot",
"automation",
"collaborative",
"Artificial Intelligence",
"technology",
"Computing",
"autonomous",
"automobile",
"cobots",
"AI",
"Integration",
"robotics",
"machine learning",
"machine",
"vision systems",
"systems",
"computerized",
"programmed",
"neural network",
"tech",
]
def analze(file):
# count = defaultdict(int)
df = pd.read_csv(file)
for text in df["Text"]:
tokenize_text = word_tokenize(text)
for w in tokenize_text:
if w in words:
count[w] += 1
analze("Articles/AppleFilter.csv")
print(count)
输出:
defaultdict(<class 'int'>, {'automation': 283, 'robot': 372, 'robotics': 194, 'machine': 220, 'tech': 41, 'systems': 187, 'technology': 246, 'autonomous': 60, 'collaborative': 18, 'automobile': 6, 'AI': 158, 'programmed': 12, 'cobots': 2, 'computerized': 3, 'Computing': 1})
目标:获取每一行的频率
{'automation': 5, 'robot': 1, 'robotics': 1, ...
{'automobile': 1, 'systems': 1, 'technology': 1,...
{'AI': 1, 'cobots: 1, computerized': 3,....
CVS 文件格式:
Title | Text | URL
我尝试了什么:
count = defaultdict(int)
df = pd.read_csv("AppleFilterTest01.csv")
for text in df["Text"].iteritems():
for row in text:
print(row)
if row in words:
count[w] += 1
print(count)
输出:
defaultdict(<class 'int'>, {})
如果有人能提供任何指导、提示或帮助,我将不胜感激。谢谢你。
【问题讨论】:
-
你能分享一个你的标记化数据集的样本
-
我相信this 帖子中的第 2 条答案可以解决您的问题。
标签: python-3.x pandas nltk