Python解决读取中文报错

关于UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte的解决办法

报错原因:UnicodeDecodeError: ‘gbk’ codec can’t decode byte

错误原因
Python 的 open 方法默认编码取决于平台,如果是 Windows 平台,默认编码是 gbk,如果文件是 utf-8 编码,就会报这个错误。

解决办法
将打开文件的代码:

open(filename, 'r')
改为:
open(filename, 'r', encoding='utf-8')

结果


问题解决,程序能正常运行了。

完整问题与代码
访问项目Gutenberg(http://gutenberg.org/ ),并找一些你想分析的图书。下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。 你可以使用方法count() 来确定特定的单词或短语在字符串中出现了多少次。例如,下面的代码计算’row’ 在一个字符串中出现了多少次:

>>> line = "Row, row, row your boat"
>>> line.count('row') 

>>> line.lower().count('row') 

请注意,通过使用lower() 将字符串转换为小写,可捕捉要查找的单词出现的所有次数,而不管其大小写格式如何。 编写一个程序,它读取你在项目Gutenberg中获取的文件,并计算单词’the’ 在每个文件中分别出现了多少次。

代码:

def count_word(filename, word):
    try:
        with open(filename, 'r', encoding='utf-8') as file_object:
            contents = file_object.read()
    except FileNotFoundError:
        print("\nSorry, the file " + filename[6:] + " doesn't exist.")
    else:
        count = contents.count(word)
        return count

file_names = ["books/Alice's Adventures in Wonderland by Lewis Carroll.txt",
              "books/The Masque of the Red Death by Edgar Allan Poe.txt",
              "books/Pride and Prejudice by Jane Austen.txt"]
keyword = 'the'

for file_name in file_names:
    count = count_word(file_name, keyword)
    if count:
        message = "\nWord '" + keyword + "' appears " + str(count) + " times in " + file_name[6:-4] + "."
        print(message)

注:此时,在 books 文件夹中暂时删除了 Alice’s Adventures in Wonderland by Lewis Carroll.txt。
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值