bash python获取文本中每个字符出现的次数

bash:

grep -o . myfile | sort |uniq -c

 

python:  使用collections模块

import pprint
import collections


f = 'xxx'
with open(f) as info:
    count = collections.Counter(info.read().upper())
    value = pprint.pformat(count)
    
    print(value)
    

 或

import codecs

f = 'xxx'
with codecs.open(f, 'r', 'utf-8') as tf:
    for l in tf:
        for ch in l:
            c[ch] = c.setdefault(ch, 0) + 1

print json.dumps(c, ensure_ascii=False, encoding='utf-8', indent=4)

 

posted @ 2018-07-05 18:01  泽锦  阅读(260)  评论(0编辑  收藏  举报