|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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)
这个代码可以帮忙解释一下,有些地方感觉不是很明白,谢谢
不知道你是哪個部分不懂
以下是我自己練習時的註解 希望有幫助到你
- 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]))) #str把list字符串化
- def pos_in_line(line, key):
- pos = [] #空的list用來儲存位置
- begin = line.find(key) #find(str, begin, end) 沒找到返回 -1
- while begin != -1:
- pos.append(begin + 1) #由於程式是0開始算 基於用戶角度是從1開始 所以+1
- begin = line.find(key, begin+1) #找到後從該key的下一個位置繼續找
- return pos #返回List 記錄位置
- def search_in_file(file_name, key):
- f = open(file_name)
- count = 0 #記錄行數
- key_dict = dict() #空字典,用來存放key(行數) : value(list表示的位子)
- for each_line in f:
- count += 1 #一行加一次
- if key in each_line:
- pos = pos_in_line(each_line, key)
- key_dict[count] = pos
- f.close()
- return key_dict #返回字典
-
- def search_files(key, detail):
- all_files = os.walk(os.getcwd()) #os.walk查找路徑下所有的子目錄 返回元祖(子目錄路徑, [包含目錄], [包含文件])
- txt_files = []
- for i in all_files:
- for each_file in i[2]: #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)
复制代码
|
|