鱼C论坛

 找回密码
 立即注册
查看: 2696|回复: 10

[已解决]写了一个小时 改的跟小甲鱼老师的代码差不多 但是就是运行会出错

[复制链接]
发表于 2021-1-3 18:12:34 | 显示全部楼层 |阅读模式

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

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

x
import os
x = input("请将该脚本放于查找的文件夹内,请输入关键字:")
y = input("请问是否需要打印关键字(%s)在文件夹中具体位置(yes/no):" % x)

#def main1(line , x):
    #list1 = []
    #for t in line.find[x]:
        #list1.append(t + 1)

    #return list1
def main1(line , x):
    list1 = []
    begin = line.find(x)
    while begin != -1:
        list1.append(begin + 1)
        begin = line.find(x , begin+1)

    return list1


def main2(file , x):
    f = open(file ) #f = open(r"file")
    p = dict() #g = dict()
    count = 0
    for h in f:
        count +=1
        if x in h:
            pos = main1(h , x)
            p[count] = pos #g[count] = pos

        f.close()
        return p #return g


def main3(p):
    x = p.keys()
    x = sorted(x)

    for temp in x:
        print("关键字出现在%s,第%s个位置;" % (temp , str(p[temp])))



def main(x , y):
    all_file = os.walk(os.getcwd())
    m = all_file
    a = []

    for i in m:
        for ea in i[2]:
            if os.path.splitext(ea)[1] == '.txt': #if os.path.splitext(ea)[1] == '.text'
                k = os.path.join(i[0],ea)
                a.append(k)

    for z in a:
        p = main2(z , x) #p = main3(z , x)
        if p: #if p:
            print("================")
            print("在文件(%s)中找到关键字(%s)" % (z , x))

            if y in ('yes','Yes','YES'):
                print(p) # print(p)
   

main(x , y)


请求各位大佬斧正,
最佳答案
2021-1-3 21:01:36

两个编码都报错了,可能原因是因为你所查找的文件夹内有多种编码的 txt 文本文件

解决方法可以去重新新建个文件夹,然后将代码移动到这个文件夹内

将需要测试的 txt 文本全部另存为,保存时候左下角有保存的编码,选择 ANSI 编码,即可

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-1-3 18:25:29 | 显示全部楼层
出现什么错误啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-1-3 18:34:05 | 显示全部楼层
bonst 发表于 2021-1-3 18:25
出现什么错误啊

这个


Traceback (most recent call last):
  File "C:/Users/pp980/Desktop/从文件中找关键字.py", line 65, in <module>
    main(x , y)
  File "C:/Users/pp980/Desktop/从文件中找关键字.py", line 56, in main
    p = main2(z , x) #p = main3(z , x)
  File "C:/Users/pp980/Desktop/从文件中找关键字.py", line 25, in main2
    for h in f:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 45: illegal multibyte sequence
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-1-3 18:42:26 | 显示全部楼层

所有的文件打开形式换个编码
  1. f = open(file,encoding='utf-8')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-1-3 18:50:16 | 显示全部楼层
txt文件打开的编码错误
这一句
  1. f = open(file)
复制代码

改成
  1. f = open(file,encoding='utf-8')
复制代码

完整代码
  1. import os
  2. x = input("请将该脚本放于查找的文件夹内,请输入关键字:")
  3. y = input("请问是否需要打印关键字(%s)在文件夹中具体位置(yes/no):" % x)

  4. #def main1(line , x):
  5.     #list1 = []
  6.     #for t in line.find[x]:
  7.         #list1.append(t + 1)

  8.     #return list1
  9. def main1(line , x):
  10.     list1 = []
  11.     begin = line.find(x)
  12.     while begin != -1:
  13.         list1.append(begin + 1)
  14.         begin = line.find(x , begin+1)

  15.     return list1


  16. def main2(file , x):
  17.     f = open(file,encoding='utf-8')
  18.     p = dict() #g = dict()
  19.     count = 0
  20.     for h in f:
  21.         count +=1
  22.         if x in h:
  23.             pos = main1(h , x)
  24.             p[count] = pos #g[count] = pos

  25.         f.close()
  26.         return p #return g


  27. def main3(p):
  28.     x = p.keys()
  29.     x = sorted(x)

  30.     for temp in x:
  31.         print("关键字出现在%s,第%s个位置;" % (temp , str(p[temp])))



  32. def main(x , y):
  33.     all_file = os.walk(os.getcwd())
  34.     m = all_file
  35.     a = []

  36.     for i in m:
  37.         for ea in i[2]:
  38.             if os.path.splitext(ea)[1] == '.txt': #if os.path.splitext(ea)[1] == '.text'
  39.                 k = os.path.join(i[0],ea)
  40.                 a.append(k)

  41.     for z in a:
  42.         p = main2(z , x) #p = main3(z , x)
  43.         if p: #if p:
  44.             print("================")
  45.             print("在文件(%s)中找到关键字(%s)" % (z , x))

  46.             if y in ('yes','Yes','YES'):
  47.                 print(p) # print(p)


  48. main(x , y)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-1-3 18:56:29 | 显示全部楼层
wuqramy 发表于 2021-1-3 18:50
txt文件打开的编码错误
这一句

加上去之后就成为这样了

Traceback (most recent call last):
  File "C:/Users/pp980/Desktop/从文件中找关键字.py", line 64, in <module>
    main(x , y)
  File "C:/Users/pp980/Desktop/从文件中找关键字.py", line 55, in main
    p = main2(z , x) #p = main3(z , x)
  File "C:/Users/pp980/Desktop/从文件中找关键字.py", line 25, in main2
    for h in f:
  File "C:\Program Files\Python39\lib\codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position 0: invalid start byte
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-1-3 18:57:00 | 显示全部楼层
昨非 发表于 2021-1-3 18:42
所有的文件打开形式换个编码

加上就成为这样了


Traceback (most recent call last):
  File "C:/Users/pp980/Desktop/从文件中找关键字.py", line 64, in <module>
    main(x , y)
  File "C:/Users/pp980/Desktop/从文件中找关键字.py", line 55, in main
    p = main2(z , x) #p = main3(z , x)
  File "C:/Users/pp980/Desktop/从文件中找关键字.py", line 25, in main2
    for h in f:
  File "C:\Program Files\Python39\lib\codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position 0: invalid start byte
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-1-3 19:07:12 | 显示全部楼层
本帖最后由 jackz007 于 2021-1-3 19:30 编辑
  1. import os

  2. def main(x , y):
  3.     for root , dirs , files in os . walk(os . getcwd()):
  4.         for file in files:
  5.             ext = os . path . splitext(file)[1] . lower()                  # 提取文件扩展名并一律转为小写字母
  6.             if ext in ('.py' , '.c' , '.cpp' , '.h' , '.txt'):             # 根据扩展名筛选符合条件的目标文件
  7.                 fn = os . path . join(root , file)                         # 合成目标文件的全路径
  8.                 f = open(fn)
  9.                 c , r , d = 0 , 0 , []                                     # c ,r 为行号、列号计数
  10.                 try:                                                       # 防止程序因读取文件出现错误而终止运行
  11.                     for txt in f:                                          # 风险语句,如果文件编码存在问题,执行此句会出错
  12.                         r = txt . find(x , 0)                              # 查找关键字,执行到此句,说明当前文件平安度过风险     
  13.                         while r != - 1:                                    # 循环查找可能出现在同一行的多个关键字
  14.                             d . append((c + 1 , r + 1))
  15.                             r = txt . find(x , r + 1)
  16.                         c += 1                                             # 当前行数加 1
  17.                 except Exception as e:                                     # 如果读取文件出现错误会到这里继续
  18.                     print('*** 错误 :文件 ["%s"] ' % fn)                  # 报告出现错误的文件名称及其路径
  19.                     print('\t' , e)                                        # 报告系统给出的错误类型及原因细节
  20.                 f . close()                                                # 无论是否出现错误,都会从这里汇合继续执行
  21.                 if d:
  22.                     print('文件 ["%s"] 中找到关键字 ["%s"]' % (fn , x))
  23.                     if y == 'yes':
  24.                         for x in d:
  25.                             print('\t第 %3d 行,%3d 列' % (x[0] , x[1]))

  26. x = input("请将该脚本放于查找的文件夹内,请输入关键字:")
  27. y = input("请问是否需要打印关键字(%s)在文件夹中具体位置(yes/no):" % x)
  28. main(x , y)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2021-1-3 21:01:36 | 显示全部楼层    本楼为最佳答案   

两个编码都报错了,可能原因是因为你所查找的文件夹内有多种编码的 txt 文本文件

解决方法可以去重新新建个文件夹,然后将代码移动到这个文件夹内

将需要测试的 txt 文本全部另存为,保存时候左下角有保存的编码,选择 ANSI 编码,即可

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

使用道具 举报

 楼主| 发表于 2021-1-3 21:37:01 | 显示全部楼层
Twilight6 发表于 2021-1-3 21:01
两个编码都报错了,可能原因是因为你所查找的文件夹内有多种编码的 txt 文本文件

解决方法可以去重新 ...

对 我之前把这个txt文件跟写好的py文件放到了桌面 才出现了这种情况
然后我将这几个文件放到了新建文件夹中
在新建的文件夹中运行这个py文件 就没有这些 错误了


谢谢大佬的解答
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-1-3 21:39:26 | 显示全部楼层

哇 这个我还没学到这些内容  看不懂
但还是谢谢大佬了 等我保存学到这些知识点后再来拜读
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-29 08:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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