|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import os
- def file_keywords(keywords):
- global dic
- for each_file in os.listdir(os.curdir):
- if not os.path.isdir(each_file):
- ext = os.path.splitext(each_file)[1]
- if ext == '.txt':
- file=open(each_file)
- count=0
- content=file.read()
- file.close()
- content=content.split('\n')
- for each_line in content:
- count+=1
- if keywords in each_line:
- key=os.getcwd()+os.sep+each_file+','+str(count)
- dic[key]=each_line.index(keywords)
- else:
- os.chdir(each_file)
- file_keywords(keywords)
- os.chdir(os.pardir)
-
- def file_print(dic):
- if dic!={}:
- print('请问是否打印出关键字【%s】在文件中的位置【yes/no】:'%keywords,end='')
- decision=input()
- if decision in ('YES','Yes','yes'):
- global list_path
- list_path=[]
- for each_key in dic:
- path=each_key.split(',')[0]
- if path not in list_path:
- list_path.append(path)
- for i in range(len(list_path)):
- print('==============================================')
- print('在文件【%s】中找到关键字【%s】'%(list_path[i],keywords))
- global dic_sort
- global dic_lines
- dic_lines={}
- dic_sort=[]
- for each in dic:
- each_path=each.split(',')[0]
- if each_path == list_path[i]:
- lines=each.split(',')[1]
- dic_lines[lines]=dic[each]
- for each_lines in dic_lines:
- dic_sort.append(int(each_lines))
- dic_sort=dic_sort.sort()
- keywords=input('请将该代码放于待查找的文件夹内,请输入关键字:')
- dic=dict()
- file_keywords(keywords)
- file_print(dic)
复制代码
这个问题就是我把变量变成global之后,发现如果不放在函数中没问题,但是放在函数中,运行之后,再查看dic_sort的值就是None,所以想问一下为什么
sort函数是对列表本身进行操作,
把49行改成
dic_sort.sort()
即可
|
|