python3.5下的一个编码问题

今天学习python,用其做了一个统计单词频数的小例子。

#coding=utf-8
import string
path = 'D:/Walden.txt'with
open(path,'r') as text:
    words = [raw_words.strip(string.punctuation).lower() for raw_words in text.read().split()]
    words_index = set(words)
    counts_dist = {index : words.count(index) for index in words_index}
file = open('D:/wordCount.txt','w')
for word in sorted(counts_dist,key=lambda x:counts_dist[x],reverse=True):
    file.write('{}-{} times'.format(word,counts_dist[word]))
file.close()
print('done')

运行时,报了一个编码错误:

UnicodeEncodeError: 'gbk' codec can't encode character '\ufeff' in position 0: illegal multibyte sequence

查了一下,发现是因为遇到了非法字符,因此在转码的过程中出现了异常,修改默认的编码为utf-8其实就可以了,然后开始查如何设置编码,最后发现如下设置:

open(path,'r','utf-8')

即可

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容