![](/img/trans.png)
[英]Count the frequency of words from a column in Python using external csv file
[英]Count the frequency of words from a column in Python
我有一個csv文件。 csv文件的結構是:
Name Hour Location
A 4 San Fransisco
B 2 New York
C 4 New York
D 7 Denton
E 8 Boston
F 1 Boston
如果你觀察上面的數據,有
2 New York and
2 Boston
我試着使用表格包。 我嘗試了表格包文檔中提到的教程超過7個小時。 但我完成了。
任何人都可以幫助我,如何使用Python提取位置列中該Csv文件中常用單詞的計數。
謝謝。
data = """Name\tHour\tLocation
A\t4\tSan Fransisco
B\t2\tNew York
C\t4\tNew York
D\t7\tDenton
E\t8\tBoston
F\t1\tBoston
"""
import csv
import StringIO
from collections import Counter
input_stream = StringIO.StringIO(data)
reader = csv.reader(input_stream, delimiter='\t')
reader.next() #skip header
cities = [row[2] for row in reader]
for (k,v) in Counter(cities).iteritems():
print "%s appears %d times" % (k, v)
輸出:
San Fransisco appears 1 times
Denton appears 1 times
New York appears 2 times
Boston appears 2 times
不確定你要分離的是什么,但示例顯示為4個空格,所以這是一個解決方案。
如果您實際上是通過制表符分隔,請使用@MariaZverina的答案
import collections
with open('test.txt') as f:
next(f) # Skip the first line
print collections.Counter(line.rstrip().rpartition(' ')[-1] for line in f)
輸出:
Counter({'New York': 2, 'Boston': 2, 'San Fransisco': 1, 'Denton': 1})
如果文件不是太大,最天真的方式是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.