python之西遊記字數統計

# -*- coding: utf-8 -*-
import sys,string,json
reload(sys)
sys.setdefaultencoding('utf8')

fr=open('xyj.txt','r')
characters=[]
stat={}

for line in fr:
    line=line.strip()

    if len(line)==0:
       continue

    #print type(line)
    line=unicode(line)

    #print type(line)
    for x in xrange(0,len(line)):
        if line[x] in [' ','\t','\n',',','.','。','!',':','“','”','?']:
            continue
        if not line[x] in characters:
            characters.append(line[x])
        if not stat.has_key(line[x]):
            stat[line[x]]=0
        stat[line[x]]+=1

fw=open('result.json','w')
fw.write(json.dumps(stat))
fw.close()

stat=sorted(stat.iteritems(),key=lambda d:d[1],reverse=True )

print type(characters[0])
for x in xrange(0,20):
    print characters[x]
print '********************************************'
print type(stat[0][0])
for x in xrange(0,20):
    print stat[x][0],stat[x][1]
fw=open('result.csv','w')
for item in stat:
    fw.write(item[0]+':'+str(item[1])+'\n')
fw.close()


fr.close()  

輸出:

<type 'unicode'>

吳
承
恩
著
第
一
回
靈
根
育
孕
源
流
出
心
性
修
持
大
********************************************
<type 'unicode'>
道 10023
不 7984
了 7144
一 7079
那 6934
我 6575
是 5907
行 5474
來 5431
他 5297
個 5206
你 5086
的 4971
者 4887
有 3909
大 3603
得 3514
這 3481
去 3377
上 3260
[Finished in 19.7s]

同時輸出json和csv

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章