0

我正在尝试计算 CSV 文件中最常见的值,并将出现的值附加到 CSV 文件中的每个项目旁边。例如:

CSV 文件:

  * 8 Values in Column 1*
  HelloWorld
  HelloWorld
  HelloSaturn
  HelloMars
  HelloPluto
  HelloSaturn
  HelloMoon
  HelloMoon

计算最常见的 Python 代码:

  #Removed Code - Take each row in CSV and append to list#
  #Create new list, count common occurrences out of 8 items
  newList = []
  counter = collections.Counter(newList)
  d = counter.most_common(8)
  print d

打印输出(在上面的 CSV 中计算了最常见的值,例如有两个“HelloWorld”):

  [('HelloWorld', 2), ('HelloMars', 1), ('HelloSaturn', 2), ('HelloPluto', 1), ('HelloMoon', 2)]

我现在正在尝试将这些值附加/插入到每个值旁边的 CSV 文件中,例如:

  * 8 Values in Column 1* *Occurrence*
  HelloWorld 2
  HelloWorld 2
  HelloSaturn 2
  HelloMars 1
  HelloPluto 1
  HelloSaturn 2
  HelloMoon 2
  HelloMoon 2

我怎样才能做到这一点?

4

2 回答 2

2

您需要使用csv.writer对象来重写 CSV 文件:

  1. 使用csv.reader将 CSV 文件读入内存(如行列表或其他内容)
  2. 使用现有代码计算发生频率
  3. 遍历您在步骤 1 中读取的每一行。使用 csv.writer 输出行中的每一列。在行的末尾,输出您在步骤 2 中计算的相应频率。

代码看起来像这样(完全未经测试):

import csv
list_of_rows = list()
with open(filename) as fin:
    reader = csv.reader(fin)
    for row in reader:
       list_of_rows.append(row)

# calculate frequency of occurrence
counter = ...

with open(filename, "w") as fout:
    writer = csv.writer(fout)
    for row in counter.most_common(8):            
        # row is now (word, frequency)
        writer.writerow(row)
于 2013-02-08T13:45:25.327 回答
1
import csv

# I fake here the opening and extracting from a CSV file
# to obtain a list of the words of the first column
ss = """HelloWorld
HelloWorld
HelloSaturn
HelloMars
HelloPluto
HelloSaturn
HelloMoon
HelloMoon"""
column = ss.splitlines()


# Now, the counting
from collections import Counter
c = Counter(column) 

# Seeing the counter we got
print '\n'.join(c)

# Putting the result in a CSV file
with open('resu.csv','wb') as g:
    gw = csv.writer(g)
    gw.writerows([item,c[item]] for item in column)
于 2013-02-09T04:17:59.550 回答