本帖最后由 keydnal_aaron 于 2018-1-18 14:17 編輯
這個測試的文本里面是英文字符串,如果環境不同,注意下文本內容的編碼方式,我的編程環境是centos7+python3.6.4
from os import walk,getcwd
from os.path import join
def search_file():
'''
查找當前目錄底下的所有文件!
return返回的結果為列表:‘/路徑/文件.txt’
'''
file_list=[]
for each_dir_file in walk(getcwd()):
if each_dir_file[2] != []:
for each_file in each_dir_file[2]:
if each_file[-4:] == '.txt':
temppath=join(each_dir_file[0],each_file)
file_list.append(temppath)
return file_list
def chazhao(filename,zfc):
'''
傳入兩個參數,文件名,要查找字符串
查找匹配字符串的行
生成結果以字典形式返回
如果文件沒有匹配字符串的行,返回空字典
:param filename:
:param zfc:
:return:
'''
count1 = 0
dict_line_weizhi = {}
file = open(filename)
for each_line in file:
count1 += 1
if zfc in each_line:
weizhi=[]
begin_zfc = each_line.find(zfc)
while begin_zfc != -1:
weizhi.append(begin_zfc)
begin_zfc = each_line.find(zfc, begin_zfc + 1)
dict_line_weizhi.setdefault(count1,weizhi)
else:
dict_line_weizhi={}
file.close()
return dict_line_weizhi
def zfc_line_weizhi(zfc,daying):
'''
接收用戶輸入需要查找的字符串zfc
接收用戶輸入是否確認查詢daying
確認查詢,返回查詢結果
確認不查詢,退出程序
:param zfc:
:param daying:
:return:
'''
if (daying == 'YES') or (daying == 'yes') or (daying == 'Yes'):
file_list = search_file()
for each_file in file_list:
result = chazhao(each_file, zfc)
if result != {}:
print('在文件' + '[' + each_file + ']' + "中找到關鍵字" + '[' + zfc + ']')
for each_key in result.keys():
print('關鍵字出現在第' + str(each_key) + '行,第' + str(result[each_key]) + '個位置!')
else:
print('退出查詢!')
if __name__ =='__main__':
zfc = input('請將該代碼放于待查找的文件夾內,請輸入關鍵字:').strip()
daying = input('請問是否打印關鍵字' + zfc + '在文件中的具體位置(YES/NO):').strip()
zfc_line_weizhi(zfc,daying)