【发布时间】:2016-05-13 22:07:12
【问题描述】:
我在 Python 脚本中尝试打开 .txt 文件,列出该文件中的单词,计算单词出现的次数(计数器)并将其放入 .csv 文件中。我的文件的名称来自 1870.txt - 1892 (1871,1872,1873..1892.txt)。那里的一切都有效,但我希望每个文件都放在下一列。
def putInExcel(outputt):
i = 1790
while i < 1892:
inputt = str(i) + '.txt' #Making text file name
writefile = open(outputt)
writer = csv.writer(writefile)
with open(inputt) as file: #Separating each word and storing in list
text = file.read().lower()
text = re.sub('[^a-z\ \']+', " ", text)
words = list(text.split())
for word in words:
cnt[word] += 1
for key, count in cnt.iteritems(): #De-dent this block
writer.writerow([key,count]) #Output both the key and the count
writefile.close()
i = i+1
此脚本正在运行,但它将所有内容存储在一列中。 有人有什么想法吗?谢谢!
【问题讨论】:
标签: python csv io text-files counter