欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

小甲鱼python课后答案40讲_小甲鱼Python 第30讲课后习题看不懂

发布时间:2023/12/9 python 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 小甲鱼python课后答案40讲_小甲鱼Python 第30讲课后习题看不懂 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

本帖最后由 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)

总结

以上是生活随笔为你收集整理的小甲鱼python课后答案40讲_小甲鱼Python 第30讲课后习题看不懂的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。