Python 创建新列并将数据存储在 .CSV 文件中

Python create new column and store data in .CSV file

我在 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

此脚本可以运行,但它会将所有内容存储在一列中。 有人知道吗?谢谢!

如果我没理解错的话,您需要一个 table,其中包含每个 year/filename 的列。在每一列中,您都需要一个数字频率计数。最左边的列是单词本身:

____     | 1790 | 1791 | 1792 | ...
Aachen       1      1     2
aardvark     1      0     0
aardwolf     0      1     0
abacus       1      2     2
acrimony     2      2     2
   :

您现在有一个相当简单的脚本,不必担心不同数据集之间的交互。当您尝试处理多个输入列表时,您将不得不以某种方式 "unify" 它们。这就是为什么我在示例中显示一些带有 0 的条目。

我的建议是掌握 setdictionary 所有看到的单词。完成后,这将是最左边的一列。

对于每个 year/input 文件,您可以单独计数。您可以将它们组织为两个平行列表:year/filename 和计数字典:

All_words = set()
Headers = []     # 1791, 1792, ...
Word_counts = [] # {'a':1, 'baa':2}, {'a':1, 'abacus': 1}, ...

现在,当您遍历文件时,将文件名和一个空字典添加到 headers/counts 列表中:

for ... 1791 ...
    Headers.append(year)
    cnt = dict()
    Word_counts.append(cnt)

像现在一样计算你的字数。但是当你统计一个词的时候,也把它加入到所有词的集合中:

        cnt[word] += 1
        All_words.add(word)

最后,当你完成后,你将不得不按照相同的顺序处理单词。所以对 All_words 的内容进行排序并使用:

row = ['Word\Year']
row.extend(Headers)
csvfile.writerow(...)

for word in sorted(All_words):
    row = [word]  # Left column is word
    row.extend([yr.get(word, 0) for yr in Word_counts])
    csvfile.writerow(...)