【问题标题】:Python create new column and store data in .CSV filePython 创建新列并将数据存储在 .CSV 文件中
【发布时间】: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


    【解决方案1】:

    如果我理解正确,您需要一个包含每个年份/文件名列的表。在每一列中,您需要一个数字频率计数。最左边的列是单词本身:

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

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

    我的建议是保留所有看到的单词的主人setdictionary。完成后,这将是最左边的列。

    对于每个年份/输入文件,您可以保留单独的计数。您可以将它们组织为两个并行列表:年份/文件名和计数字典:

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

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

    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(...)            
    

    【讨论】:

    • 这正是我想要的!但我正在尝试理解并将代码与我的代码联系起来
    • 我不明白 ...1791 ... 的“...”是什么意思。抱歉,我很难从一个代码转移到另一个代码 :)
    • 它的意思是“你需要放在这里的任何东西”。我试图弄清楚它在哪个循环中。
    猜你喜欢
    • 1970-01-01
    • 2017-03-26
    • 2022-01-16
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2020-06-02
    相关资源
    最近更新 更多