设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 12623|回复: 1
打印 上一主题 下一主题

求助!统计txt中词频出错

[复制链接]

4

主题

0

好友

34

积分

新手上路

Rank: 1

跳转到指定楼层
楼主
发表于 2018-7-25 17:45:03 |只看该作者 |倒序浏览
# -*- coding: utf-8 -*-

import sys,re
import importlib

importlib.reload(sys)

text = open('C:/Users/Administrator/Desktop/wordstata.txt','rb').read()
wfile=open('result.txt','w')
txet = text.decode('utf-8')

r = re.compile('[\x80-\xff]+')
m = r.findall(text)
dict={}
z1 = re.compile('[\x80-\xff]{2}')
z2 = re.compile('[\x80-\xff]{4}')
z3 = re.compile('[\x80-\xff]{6}')
z4 = re.compile('[\x80-\xff]{8}')
for i in m:
    x = i.encode('gb18030')
    i = z1.findall(x)
    for j in i:
        if(j in dict):
            dict[j]+=1

dict=sorted(dict.items(), key=lambda d:d[1])
for a,b in dict:
    if b>0:
        wfile.write(a+','+str(b)+'\n')


Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/wordstatabytxt.py", line 10, in <module>
    txet = text.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte              

回复

使用道具 举报

174

主题

45

好友

11万

积分

管理员

Rank: 9Rank: 9Rank: 9

沙发
发表于 2018-7-26 18:44:24 |只看该作者
open('C:/Users/Administrator/Desktop/wordstata.txt','r', encoding='utf8')

不要用b模式,直接设编码。如果utf8不行就改gbk
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-9-23 04:34 , Processed in 0.013592 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部