您的位置:首页 > 编程语言 > Python开发

python之西游记字数统计

2017-01-09 20:38 381 查看
# -*- 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 [' ',
4000
'\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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: