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

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

  • 问题描述
  • 错误原因
  • 解决办法
  • 结果
  • 完整问题与代码

问题描述

最近在学《Python编程:从入门到实践》,在做到例题 10-10:常见单词时遇到了如下报错信息:

报错原因: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') 

2 

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

3

请注意,通过使用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。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年7月12日
下一篇 2023年7月12日

相关推荐