入土 发表于 2020-4-4 20:38:00

为什么递归失败?

import os

def key(word):
    def pos(each_line,word):
      line_pos = []
      begin = line.find(word)
      while begin != -1:
            line_pos.append(begin + 1)
            begin = each_line.find(key,begin+1)
            print(1)
    def open_file(each_file):
      global file_way
      print(2)
      f = open(file_way)
      count_line = 0
      for each_line in f:
            count_line += 1
            if word in each_line: #开始索引
                pos(each_line,word)
                print('关键字出现在%d行,第[%s]个位置' %(count_line,str(line_pos)))
      f.close()
    def y(word):
      for each_file in os.listdir(os.curdir):
            print(3)
            outreach = os.path.splitext(each_file)
            if outreach == 'txt':   #先判断文件扩展名是否为txt文件
                file_way = os.curdir + os.sep + each_file
                open_file(each_file) #打开函数
            if os.path.isdir(each_file):
                y(each_file)
                os.chdir(os.pardir)
    discuss = input('请问是否需要打印关键字【%s】在文件中的具体文职(YES/NO):')
    if discuss == 'YES' or discuss == 'yes':
      y(word)
word = input('请将该脚本放于待查找的文件夹内,请输入关键字:')

key(word)




小甲鱼的二师兄 发表于 2020-4-4 20:52:24

递归层数太多了,超出了系统的设定……

dlnb526 发表于 2020-4-4 21:01:10

本帖最后由 dlnb526 于 2020-4-4 21:04 编辑

emmm首先,你的缩进都是用空格的呀~~调试好费劲。建议下次用tab键~~然后,
    def y(word):

      for each_file in os.listdir(os.curdir):
            outreach = os.path.splitext(each_file)
            if outreach == 'txt':   #先判断文件扩展名是否为txt文件
                file_way = os.curdir + os.sep + each_file
                open_file(each_file) #打开函数
            if os.path.isdir(each_file):
                print(each_file)
                y(each_file)
                os.chdir(os.pardir)
    discuss = input('请问是否需要打印关键字【%s】在文件中的具体文职(YES/NO):')
    if discuss == 'YES' or discuss == 'yes':
      y(word)

如上通过打印调试
是这里没有迭代出,一直在第一个文件夹循环呢~重新检查迭代条件吧

问题在于你传入的word参数没有用~~~emmm所以自然一直在这一层迭代了

入土 发表于 2020-4-4 21:54:19

dlnb526 发表于 2020-4-4 21:01
emmm首先,你的缩进都是用空格的呀~~调试好费劲。建议下次用tab键~~然后,




好吧,txt前面少了一个点
页: [1]
查看完整版本: 为什么递归失败?