【发布时间】:2011-06-30 23:41:43
【问题描述】:
我正在尝试通过 csv.DictReader 获取一个 csv 文件并将其转换为字典。这样做之后,我想修改字典的其中一列,然后将数据写入 tsv 文件。我正在处理文本中的单词和词频。
我尝试使用 dict.value() 函数获取字典值,但我收到一条错误消息,提示“AttributeError: DictReader instance has no attribute "values"”
下面是我的代码:
#calculate frequencies of each word in Jane Austen's "Pride and Prejudice"
import csv
#open file with words and counts for the book, and turn into dictionary
fob = open("P&P.csv", "r")
words = csv.DictReader(fob)
dict = words
#open a file to write the words and frequencies to
fob = open("AustenWords.tsv", "w")
#set total word count
wordcount = 120697
for row in words:
values = dict.values()
print values
基本上,我有文本中每个单词的总计数(即“a”,“1937”),我想找到相关单词使用的总单词计数的百分比(因此,对于“a ",百分比将是 1937/120697。)现在我的代码没有执行此操作的等式,但我希望,一旦我获得每一行的值,用单词和计算的百分比。如果有人有更好的方法(或任何方法!)来做到这一点,我将不胜感激。
谢谢
【问题讨论】:
标签: csv dictionary