如何计算csv中的字符?

时间:2018-11-16 07:08:39

标签: python pandas csv collections

我的CSV具有以下数据

['value']
['abcd']
['def abc']

我想按值的降序计数每个字符,值是csv文件中的标题。我在下面写了一个脚本。有没有比这更好的脚本了?

from csv import DictReader
with open("name.csv") as f:
    a1 = [row["value"] for row in DictReader(f)]
#a1
from collections import Counter
counts = Counter()
for line in a1:
    counts.update(list((line)))
    x=dict(counts)
from collections import defaultdict
d = defaultdict(int)
for w in sorted(x, key=x.get, reverse=True):
  print (w, x[w])

1 个答案:

答案 0 :(得分:1)

from collections import defaultdict
path = "name.csv"
d_list = defaultdict(int)

with open(path, 'r') as fl:
    for word in fl:
        for ch in word:
            #if word[0] == ch:
               dd[ch] += 1

del d_list['\n']
del d_list[' ']
#print (d_list)

dd = sorted(d_list.items(), key=lambda v:v[1], reverse=True)
#dd_lex = sorted(dd, key = lambda k: (-k[1],k[0]))

for el in dd:
    print (el[0] + ' '+ str(el[1]))