我使用的是計算給定文本文檔中單詞出現率的代碼,現在我希望將輸出保存爲具有兩列的csv文件:一個用於單詞,一個用於頻率。用兩列|創建一個csv文件計數器模式
這是我試圖複製代碼:
from collections import Counter
counter = Counter(['spam', 'egg', 'spam', 'egg', 'python', 'egg'])
with open('wordfile.csv', 'w') as f:
writer = csv.writer(f, delimiter=' ')
writer.writerow(('word', 'count'))
writer.writerows(counter.most_common())
然而,這是輸出:
word countegg 3spam 2python 1
,我試圖讓輸出應該只包含兩列(一個用於「單詞」,另一個用於「頻率」,並且每行應該包含文本及其在文本中的出現:
word, frequency,
the, 3165,
in, 1265,
of,1233,
當我打印的代碼輸出:
print(open('wordfile.csv', 'rb').read())
我得到:
b'word count\r\r\negg 3\r\r\nspam 2\r\r\npython 1\r\r\n')
正如你可以看到有沒有兩列字和頻率。 我使用Windows,這是我使用的Python版本:3.5.2 |蟒蛇4.1.1(64位)
對於寫CSV,它往往容易簡單地使用[file.write()](HTTPS寫的值://文檔.python.org/2 /庫/ stdtypes.html#file.write)。 – GreenMatt