3.上周习题

3. 捋这个题逻辑

编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符)

 

# key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
# detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES):' % key)
# search_files(key, detail)


import os       # ①导入os模块

def search_files(key, detail):   
    all_files = os.walk(os.getcwd())  # os.getcwd() 将当前工作目录路径作为字符串获取
    txt_files = []                    # os.walk() 目录树中游走输出在目录中的文件名
 
    for i in all_files:               # os.walk(os.getcwd()) 输出所有文件工作目录路径名
        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)     # 判断为 .txt 后缀并以列表形式输出
 
    for each_txt_file in txt_files:
        key_dict = search_in_file(each_txt_file, key)  # 内嵌search_in_file()函数,运行
        if key_dict:
            print('================================================================')
            print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
            if detail in ['YES', 'Yes', 'yes']:
                print_pos(key_dict)               # 内嵌并输出pos()函数(位置)


def search_in_file(file_name, key):
    f = open(file_name)    #开目标文件
    count = 0 
    key_dict = dict()       #构建字典
    
    for each_line in f:
        count += 1                        #搜索到 次数+1
        if key in each_line:   #搜索关键字 ↑
            pos = pos_in_line(each_line, key)   #获取位置
            key_dict[count] = pos        # 构成次数与位置的一一对应的键值对
    
    f.close()                           #关文件保存
    return key_dict                     #返回字典的形式 

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:                #用户看到的是“1”,故 +1
        pos.append(begin + 1) 
        begin = line.find(key, begin+1) 
 
    return pos                 #返回位置列表
 
 

 
key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES):' % key)
search_files(key, detail)

4.用pathlib方法复现

1 编写一个程序,统计当前目录下每个文件类型的文件数  

from pathlib import Path
 
type_dict = dict()
for each in Path().iterdir():
    if each.is_dir():              
        type_dict.setdefault('文件夹', 0)        #查找文件夹,若没有报错,返回值为0
        type_dict['文件夹'] += 1
    else:
        ext =each.suffix               #获取文件后缀
        type_dict.setdefault(ext, 0)   #同理,查找后缀,若没有报错,返回值为0
        type_dict[ext] += 1
        
for each_type in type_dict.keys():      #输出
    print('该文件夹下共有类型为【%s】的文件 %d 个' % (each_type, type_dict[each_type]))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值