• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
UestcXiye
帮助1

问题描述

最近在学《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。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgcafii
系列文章
更多 icon
同类精品
更多 icon
继续加载