鱼C论坛

 找回密码
 立即注册
查看: 2512|回复: 11

零基础入门python第30讲课后第4题出现错误,请问怎么解决

[复制链接]
发表于 2020-3-3 11:24:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
30讲4题遇到错误,代码打了一遍不对,直接拷贝的小甲鱼的答案,还是这个错误,请问怎么处理:

请将该脚本放于待查找的文件夹内,请输入关键字:小甲鱼
请问是否需要打印关键字【小甲鱼】在文件中的具体位置(YES/NO):yes
Traceback (most recent call last):
  File "D:\homework5.py", line 56, in <module>
    search_files(key, detail)
  File "D:\homework5.py", line 46, in search_files
    key_dict = search_in_file(each_txt_file, key)
  File "D:\homework5.py", line 25, in search_in_file
    for each_line in f:
  File "D:\Python36\lib\codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 16: invalid start byte
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-3-3 11:25:17 | 显示全部楼层
把小甲鱼的代码发上来
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-3 11:25:58 | 显示全部楼层
zltzlt 发表于 2020-3-3 11:25
把小甲鱼的代码发上来

import os

def print_pos(key_dict):
    keys = key_dict.keys()
    keys = sorted(keys) # 由于字典是无序的,我们这里对行数进行排序
    for each_key in keys:
        print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))


def pos_in_line(line, key):
    pos = []
    begin = line.find(key)
    while begin != -1:
        pos.append(begin + 1) # 用户的角度是从1开始数
        begin = line.find(key, begin+1) # 从下一个位置继续查找

    return pos


def search_in_file(file_name, key):
    f = open(file_name)
    count = 0 # 记录行数
    key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
   
    for each_line in f:
        count += 1
        if key in each_line:
            pos = pos_in_line(each_line, key) # key在每行对应的位置
            key_dict[count] = pos
   
    f.close()
    return key_dict


def search_files(key, detail):   
    all_files = os.walk(os.getcwd())
    txt_files = []

    for i in all_files:
        for each_file in i[2]:
            if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
                each_file = os.path.join(i[0], each_file)
                txt_files.append(each_file)

    for each_txt_file in txt_files:
        key_dict = search_in_file(each_txt_file, key)
        if key_dict:
            print('================================================================')
            print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
            if detail in ['YES', 'Yes', 'yes']:
                print_pos(key_dict)


key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
search_files(key, detail)
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-3 11:28:12 | 显示全部楼层
这样试试:

  1. import os

  2. def print_pos(key_dict):
  3.     keys = key_dict.keys()
  4.     keys = sorted(keys) # 由于字典是无序的,我们这里对行数进行排序
  5.     for each_key in keys:
  6.         print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))


  7. def pos_in_line(line, key):
  8.     pos = []
  9.     begin = line.find(key)
  10.     while begin != -1:
  11.         pos.append(begin + 1) # 用户的角度是从1开始数
  12.         begin = line.find(key, begin+1) # 从下一个位置继续查找

  13.     return pos


  14. def search_in_file(file_name, key):
  15.     f = open(file_name, encoding="utf-8")
  16.     count = 0 # 记录行数
  17.     key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
  18.    
  19.     for each_line in f:
  20.         count += 1
  21.         if key in each_line:
  22.             pos = pos_in_line(each_line, key) # key在每行对应的位置
  23.             key_dict[count] = pos
  24.    
  25.     f.close()
  26.     return key_dict


  27. def search_files(key, detail):   
  28.     all_files = os.walk(os.getcwd())
  29.     txt_files = []

  30.     for i in all_files:
  31.         for each_file in i[2]:
  32.             if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
  33.                 each_file = os.path.join(i[0], each_file)
  34.                 txt_files.append(each_file)

  35.     for each_txt_file in txt_files:
  36.         key_dict = search_in_file(each_txt_file, key)
  37.         if key_dict:
  38.             print('================================================================')
  39.             print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
  40.             if detail in ['YES', 'Yes', 'yes']:
  41.                 print_pos(key_dict)


  42. key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
  43. detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
  44. search_files(key, detail)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-3 11:30:09 | 显示全部楼层

还是报错

Traceback (most recent call last):
  File "D:\homework5.py", line 56, in <module>
    search_files(key, detail)
  File "D:\homework5.py", line 46, in search_files
    key_dict = search_in_file(each_txt_file, key)
  File "D:\homework5.py", line 25, in search_in_file
    for each_line in f:
  File "D:\Python36\lib\codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 16: invalid start byte
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-3 11:31:38 | 显示全部楼层
fengyunkuang 发表于 2020-3-3 11:30
还是报错

Traceback (most recent call last):

这样呢:

  1. import os

  2. def print_pos(key_dict):
  3.     keys = key_dict.keys()
  4.     keys = sorted(keys) # 由于字典是无序的,我们这里对行数进行排序
  5.     for each_key in keys:
  6.         print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))


  7. def pos_in_line(line, key):
  8.     pos = []
  9.     begin = line.find(key)
  10.     while begin != -1:
  11.         pos.append(begin + 1) # 用户的角度是从1开始数
  12.         begin = line.find(key, begin+1) # 从下一个位置继续查找

  13.     return pos


  14. def search_in_file(file_name, key):
  15.     f = open(file_name, encoding="gbk")
  16.     count = 0 # 记录行数
  17.     key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
  18.    
  19.     for each_line in f:
  20.         count += 1
  21.         if key in each_line:
  22.             pos = pos_in_line(each_line, key) # key在每行对应的位置
  23.             key_dict[count] = pos
  24.    
  25.     f.close()
  26.     return key_dict


  27. def search_files(key, detail):   
  28.     all_files = os.walk(os.getcwd())
  29.     txt_files = []

  30.     for i in all_files:
  31.         for each_file in i[2]:
  32.             if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
  33.                 each_file = os.path.join(i[0], each_file)
  34.                 txt_files.append(each_file)

  35.     for each_txt_file in txt_files:
  36.         key_dict = search_in_file(each_txt_file, key)
  37.         if key_dict:
  38.             print('================================================================')
  39.             print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
  40.             if detail in ['YES', 'Yes', 'yes']:
  41.                 print_pos(key_dict)


  42. key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
  43. detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
  44. search_files(key, detail)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-3 11:33:15 | 显示全部楼层

还是有错
Traceback (most recent call last):
  File "D:\homework5.py", line 56, in <module>
    search_files(key, detail)
  File "D:\homework5.py", line 46, in search_files
    key_dict = search_in_file(each_txt_file, key)
  File "D:\homework5.py", line 25, in search_in_file
    for each_line in f:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xb4 in position 17: illegal multibyte sequence
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-3 11:38:59 | 显示全部楼层
用记事本打开你的文件,选择另存为,将右下角的编码改为 UTF-8 再保存。

然后用这段代码试试:

  1. import os

  2. def print_pos(key_dict):
  3.     keys = key_dict.keys()
  4.     keys = sorted(keys) # 由于字典是无序的,我们这里对行数进行排序
  5.     for each_key in keys:
  6.         print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))


  7. def pos_in_line(line, key):
  8.     pos = []
  9.     begin = line.find(key)
  10.     while begin != -1:
  11.         pos.append(begin + 1) # 用户的角度是从1开始数
  12.         begin = line.find(key, begin+1) # 从下一个位置继续查找

  13.     return pos


  14. def search_in_file(file_name, key):
  15.     f = open(file_name, encoding="utf-8")
  16.     count = 0 # 记录行数
  17.     key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
  18.    
  19.     for each_line in f:
  20.         count += 1
  21.         if key in each_line:
  22.             pos = pos_in_line(each_line, key) # key在每行对应的位置
  23.             key_dict[count] = pos
  24.    
  25.     f.close()
  26.     return key_dict


  27. def search_files(key, detail):   
  28.     all_files = os.walk(os.getcwd())
  29.     txt_files = []

  30.     for i in all_files:
  31.         for each_file in i[2]:
  32.             if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
  33.                 each_file = os.path.join(i[0], each_file)
  34.                 txt_files.append(each_file)

  35.     for each_txt_file in txt_files:
  36.         key_dict = search_in_file(each_txt_file, key)
  37.         if key_dict:
  38.             print('================================================================')
  39.             print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
  40.             if detail in ['YES', 'Yes', 'yes']:
  41.                 print_pos(key_dict)


  42. key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
  43. detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
  44. search_files(key, detail)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-3 11:45:12 | 显示全部楼层
zltzlt 发表于 2020-3-3 11:38
用记事本打开你的文件,选择另存为,将右下角的编码改为 UTF-8 再保存。

然后用这段代码试试:

可以查到了,不过是这样提示的:

在文件【D:\看一看.txt】中找到关键字【小甲鱼】
关键字出现在第 1 行,第 [2] 个位置。
Traceback (most recent call last):
  File "D:\homework5.py", line 56, in <module>
    search_files(key, detail)
  File "D:\homework5.py", line 46, in search_files
    key_dict = search_in_file(each_txt_file, key)
  File "D:\homework5.py", line 25, in search_in_file
    for each_line in f:
  File "D:\Python36\lib\codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 16: invalid start byte
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-3 11:46:18 | 显示全部楼层
fengyunkuang 发表于 2020-3-3 11:45
可以查到了,不过是这样提示的:

在文件【D:\看一看.txt】中找到关键字【小甲鱼】

另存为时编码改为 UTF-8 了吗 ?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-3 12:06:43 From FishC Mobile | 显示全部楼层
zltzlt 发表于 2020-3-3 11:46
另存为时编码改为 UTF-8 了吗 ?

改了,否则是查不到的,我看默认是ansi模式存的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-3 16:32:10 | 显示全部楼层
有没有大佬能解答下,如果大家的都好用,是我的什么设置不对吗?

File "D:\Python36\lib\codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
这个什么意思?

在文件【D:\看一看.txt】中找到关键字【小甲鱼】
关键字出现在第 1 行,第 [2] 个位置。
Traceback (most recent call last):
  File "D:\homework5.py", line 56, in <module>
    search_files(key, detail)
  File "D:\homework5.py", line 46, in search_files
    key_dict = search_in_file(each_txt_file, key)
  File "D:\homework5.py", line 25, in search_in_file
    for each_line in f:
  File "D:\Python36\lib\codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 16: invalid start byte
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-23 03:00

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表