鱼C论坛

 找回密码
 立即注册
查看: 803|回复: 1

30课课后题4请教

[复制链接]
发表于 2018-3-5 19:00:27 | 显示全部楼层 |阅读模式

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

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

x
  1. import os

  2. def find_repeat(source, elmt):
  3.     elmt_index=[]
  4.     s_index = 0;e_index = len(source)
  5.     while(s_index < e_index):
  6.         try:
  7.             temp = source.index(elmt,s_index,e_index)
  8.             elmt_index.append(temp)
  9.             s_index = temp + 1
  10.         except ValueError:
  11.             break
  12.     return elmt_index

  13. def Fun5(address, keywords):
  14.     global choose
  15.     a = list(os.listdir(address))
  16.     for each in a:
  17.         if os.path.isfile(address + '\\' + each):
  18.             if (os.path.splitext(each)[1]) == ".txt":
  19.                 f = open(address + '\\' + each ,'r')
  20.                 line = 0
  21.                 context = ''
  22.                 for each_line in f:
  23.                     context += each_line
  24.                 if keywords in context:
  25.                     print("=================================================================")
  26.                     print("在文件【%s】中找到关键字【%s】"%((address + '\\' + each),keywords))
  27.                 f = open(address + '\\' + each ,'r')
  28.                 for each_line in f:
  29.                     line += 1
  30.                     if (keywords in each_line) and (choose == ("yes" or "YES" or "Yes")):
  31.                         print("关键字出现在第%d行,第%s个位置。"%(line,str(find_repeat(each_line,keywords))))
  32.                 f.close()
  33.         elif os.path.isdir(address + '\\' + each):
  34.             Fun5((address + '\\' + each), keywords)
  35.    

  36. keywords = input("请将该代码放于带查找的文件夹内,请输入关键字:")
  37. choose = input("请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):"%keywords)
  38. address = os.path.abspath('.')
  39.                               
  40. Fun5(address, keywords)
复制代码


运行后显示:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence
请问是什么原因导致这个Error的?
2018-03-05_185854.jpg
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-3-5 19:09:23 | 显示全部楼层
应该是这两句
  1. f = open(address + '\\' + each ,'r')
  2.                 for each_line in f:
复制代码

把第一句改成
  1. f = open(address + '\\' + each ,'r', encoding='utf-8')
  2.               
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-12-28 08:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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