2013-02-08 32 views
0

我正在嘗試計算CSV文件中最常見的值,並在CSV文件中的每個項目旁邊添加匹配項的值。例如:Python匹配列表並返回找到的值

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 

我該怎麼做?

+0

使用[了'csv'模塊](http://docs.python.org/3/library/csv.html#csv.writer)。 – 2013-02-08 13:45:27

+0

@ZeeeeeV我不明白你爲什麼使用most_common(8),因爲你似乎在生成的CSV文件中保持相同的順序。 – eyquem 2013-02-09 04:32:54

回答

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) 
+0

這個解決方案很有效,謝謝! with函數中的'd'屬性應該是'c'。再次感謝! – ZeeeeeV 2013-02-09 12:58:27

2

您需要使用csv.writer對象重寫CSV文件:使用csv.reader

  • 使用計算的出現頻率

    1. 閱讀CSV文件到內存中(如行或東西的清單)您現有的代碼
    2. 迭代您在步驟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) 
    
  • +0

    謝謝。我正試圖實施這個解決方案。 'counter.frequency_of'是什麼意思?我收到錯誤'counter object has no attribute frequency'' – ZeeeeeV 2013-02-08 16:11:57

    +0

    那部分是僞代碼。我更新了正確使用計數器的答案。 – misha 2013-02-09 03:43:26

    相關問題