小甲鱼python课后答案40讲_小甲鱼Python 第30讲课后习题看不懂
本帖最后由 keydnal_aaron 于 2018-1-18 14:17 編輯
這個測試的文本里面是英文字符串,如果環(huán)境不同,注意下文本內(nèi)容的編碼方式,我的編程環(huán)境是centos7+python3.6.4
from os import walk,getcwd
from os.path import join
def search_file():
'''
查找當(dāng)前目錄底下的所有文件!
return返回的結(jié)果為列表:‘/路徑/文件.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):
'''
傳入兩個參數(shù),文件名,要查找字符串
查找匹配字符串的行
生成結(jié)果以字典形式返回
如果文件沒有匹配字符串的行,返回空字典
: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
接收用戶輸入是否確認(rèn)查詢daying
確認(rèn)查詢,返回查詢結(jié)果
確認(rèn)不查詢,退出程序
: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 + ']' + "中找到關(guān)鍵字" + '[' + zfc + ']')
for each_key in result.keys():
print('關(guān)鍵字出現(xiàn)在第' + str(each_key) + '行,第' + str(result[each_key]) + '個位置!')
else:
print('退出查詢!')
if __name__ =='__main__':
zfc = input('請將該代碼放于待查找的文件夾內(nèi),請輸入關(guān)鍵字:').strip()
daying = input('請問是否打印關(guān)鍵字' + zfc + '在文件中的具體位置(YES/NO):').strip()
zfc_line_weizhi(zfc,daying)
總結(jié)
以上是生活随笔為你收集整理的小甲鱼python课后答案40讲_小甲鱼Python 第30讲课后习题看不懂的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript之闭包
- 下一篇: python大纲图_Python课程大纲