ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python编程练习(五):41 - 50

2021-05-20 07:56:55  阅读:200  来源: 互联网

标签:key Python 50 41 file each path txt os


零基础入门学Python系列内容对应的所有编程练习题目 → \rightarrow →Python编程练习题目汇总

  1. 编写程序:用户输入开始搜索的路径,查找该路径下(包含子文件夹内)所有的视频格式文件(要求查找mp4 rmvb, avi的格式即可),并把创建一个文件(vedioList.txt)存放所有找到的文件的路径。
import os

def search_file(start_dir, target) :
    os.chdir(start_dir)
    
    for each_file in os.listdir(os.curdir) :
        ext = os.path.splitext(each_file)[1]
        if ext in target :
            vedio_list.append(os.getcwd() + os.sep + each_file + os.linesep)  # 使用os.sep是程序更标准
        if os.path.isdir(each_file) :
            search_file(each_file, target)                         # 递归调用
            os.chdir(os.pardir)                                         # 递归调用后切记返回上一层目录

start_dir = input('请输入待查找的初始目录:')
program_dir = os.getcwd()

target = ['.mp4', '.avi', '.rmvb']
vedio_list = []

search_file(start_dir, target)

f = open(program_dir + os.sep + 'vedioList.txt', 'w')
f.writelines(vedio_list)
f.close()

  >>>
  请输入待查找的初始目录:E:\学习资料\Literature\学术论文文献阅读与机助汉英翻译
  >>>

在这里插入图片描述

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

#================打印结果==================
#此函数主用于search_files函数需要打印具体位置时,调用此函数将字典类型排序,打印对应行数及位置。
def print_pos(key_dict):
    keys = key_dict.keys()         #分离字典的key
    keys = sorted(keys)            #由于字典是无序的,我们这里对行数进行排序#sorted()函数就可以对list进行排序
    for each_key in keys:
        print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))

#================在某行查找关键字==================
#此函数主用于定位关键字所在行的位置,返给serch_in_file写入字典value.
def pos_in_line(line, key):
    pos = []
    begin = line.find(key)       #查找关键字在每一行中的位置,赋值给begin #find方法不包含索引值会返回-1
    while begin != -1:           #不为-1时代表找到了,建议了解下find函数。
        pos.append(begin + 1)    # 用户的角度是从1开始数
        begin = line.find(key, begin+1)   # 从下一个位置继续查找

    return pos

#================在文件中查找==================
#此函数主用于将文件以行数为索引的key,关键字在行的位置作为value作为字典类型,调用pos_in_line函数处理,将字典返回给search_files函数。
def search_in_file(file_name, key):
    f = open(file_name,encoding='gbk',errors='ignore')        #打开文本文件
    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在每行对应的位置  调用pos_in_line函数 传入这个行和关键字
            key_dict[count] = pos
    
    f.close()
    return key_dict

#================主程序(在目录中查找)==================
#此函数主用于遍历当前目录下可以打开的txt文档,然后调用search_in_file函数进行处理。
def search_files(key, detail):    #第一步调用search_file函数 把 key, detail 参数传入进去
    all_files = os.walk(os.getcwd())  #遍历当前目录下的所有文档,返回一个三目元祖(0.目录,1.包含路径,2.包含文件),将返回的结果赋值给all_files
    txt_files = []   #定义列表txt_files 

    for i in all_files:   #遍历all_files  注意这里的i为单次遍历的三元组,也就是说,这里的i是包含目录、路径和文件的三元组。
        for each_file in i[2]:  #遍历三元组的第三个值,即遍历文件,这里的each_file为单次遍历的文件
            if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
                each_file = os.path.join(i[0], each_file)  #如果each_file 是文本文件  则将该文件的路径名称以及文件名称合并,并赋值给each_file 
                txt_files.append(each_file)  #列表txt_files 中追加each_file 此时的each_file为全路径含文件名 列表中追加的文本文件全路径

    for each_txt_file in txt_files:  #在列表txt_file中 遍历所有的文本文件 each_txt_file为单次遍历的文本文件名
        key_dict = search_in_file(each_txt_file, key)  #调用seach_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('请将该脚本放于待查找的文件夹内,请输入关键字:')   #接受用户输入的关键字 key为用户输入的结果
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)  #请示用户是否打印  detail为请示结果
search_files(key, detail)  #调用函数search_files 传入关键字 key, detail 

  >>>
  请将该脚本放于待查找的文件夹内,请输入关键字:和尚
  请问是否需要打印关键字【和尚】在文件中的具体位置(YES/NO):YES
  在文件【E:\学习资料\Python\my codes\story.txt】中找到关键字【和尚】
  关键字出现在第 3 行,第 [6, 11] 个位置。
  关键字出现在第 7 行,第 [6, 11] 个位置。
  >>>

  1. 编写程序:要求使用pickle将文件里的对话按照以下要求腌制成不同文件。
#将文件(file.txt)中的数据进行分割并按照以下规则保存起来:
#(1)将儿子的对话单独保存为 son_*.txt 的文件去掉“儿子:”)
#(2)将妈妈的对话单独保存为 mom_*.txt 的文件去掉“妈妈:”)
#(3)文件中总共有三段对话。分别保存为son_1.txt、mom_1.txt、son_2.txt、mom_2.txt、son_3.txt、mom_3.txt共6个文件(提示:文件中不同的对话间已使用“==============”分割)

import pickle
def save_pickle_file(son,mom,count):
    file_name_son = 'son_' + str(count) + '.txt'
    file_name_mom = 'mom_' + str(count) + '.txt'
 
    son_pickle_file = open(file_name_son,'wb')
    mom_pickle_file = open(file_name_mom,'wb')
 
    pickle.dump(son,son_pickle_file)
    pickle.dump(mom,mom_pickle_file)
 
    son_pickle_file.close()
    mom_pickle_file.close()
 
def split_file(file_name):
    f = open(file_name)
    son = []
    mom = []
    count = 1
 
    for each_line in f:
        if each_line[:6] != '======':
            (role,line_spoken) = each_line.split(':',1)
            if role == '儿子':
                son.append(line_spoken)
            elif role == '妈妈':
                mom.append(line_spoken)
        else:
            save_pickle_file(son,mom,count)
            count += 1
            son = []
            mom = []
 
    save_pickle_file(son,mom,count)
 
    f.close()
 
split_file('newfile.txt')

  >>>

在这里插入图片描述

  1. 编写程序:当用户输入整数的时候正常返回,否则提示出错并要求重新输入。
# 尝试一个新的函数int_input(),当用户输入整数的时候正常返回,否则提示出错并要求重新输入。
def int_input(prompt=''):
    while True:
        try:
            int(input(prompt))
            break
        except ValueError:
            print('出错,您输入的不是整数!')

int_input('请输入一个整数:')

  >>>
  请输入一个整数:a
  出错,您输入的不是整数!
  请输入一个整数:7

  1. 编写程序:GUI——一个小游戏(msgbox、ccbox)。
import easygui as g
import sys

while 1:
    g.msgbox('嗨,欢迎进入第一个界面小游戏^_^')
    msg = "请问您希望可以学到什么知识呢?"
    title = "小游戏互动"
    choices = ["编程","demo","算法","理论知识"]
    choice = g.choicebox(msg,title,choices)
    g.msgbox("您的选择是:" + str(choice), "结果")
    msg = "您希望重新开始小游戏吗?"
    title = "请选择"
    if g.ccbox(msg,title):  #show a Continue/Cancel dialog
        pass  #user chose Continue
    else:
        sys.exit(0)  #user chose Cancel

  >>>
  OK
  >>>

  1. 编写程序:GUI——用户输入路径查找该路径下所有的视频格式文件(choicebox、multchoicebox)。
import easygui as g

target = ['.mp4','.avi','.rmvb','.mkv','.torrent']
vedio_list = []

import os
def serach_file(start_dir,target):
    os.chdir(start_dir)

    for each_file in os.listdir(os.curdir):
        ext = os.path.splitext(each_file)[1]
        if ext in target:
            vedio_list.append(os.getcwd() + os.sep +each_file + os.linesep)
        if os.path.isdir(each_file):
            serach_file(each_file,target)
            os.chdir(os.pardir)
start_dir = input('请输入需要查找的目录:')
program_dir = os.getcwd()
serach_file(start_dir,target)

f = open(program_dir + os.sep + 'gui1——vedioList.txt','w')
f.writelines(vedio_list)
f.close()

# g.choicebox(msg='在 【%s】 系列路径下工搜索满足条件的文件如下' % start_dir,choices=vedio_list)


g.multchoicebox(msg='在 【%s】 系列路径下工搜索满足条件的文件如下' % start_dir,choices=vedio_list)
# multchoicebox()函数也是提供一个可选择的列表,与choicebox()不同的是,multchoicebox()支持用户选择0个,1个或者同时选择多个选项。

  >>>
  请输入需要查找的目录:E:\学习资料\Literature\学术论文文献阅读与机助汉英翻译
  >>>

在这里插入图片描述

  1. 编写程序:GUI——用户输入路径查找该路径下所有的视频格式文件(choicebox、multchoicebox)。
import easygui as g

target = ['.mp4','.avi','.rmvb','.mkv','.torrent']
vedio_list = []

import os
def serach_file(start_dir,target):
    os.chdir(start_dir)

    for each_file in os.listdir(os.curdir):
        ext = os.path.splitext(each_file)[1]
        if ext in target:
            vedio_list.append(os.getcwd() + os.sep +each_file + os.linesep)
        if os.path.isdir(each_file):
            serach_file(each_file,target)
            os.chdir(os.pardir)
start_dir = input('请输入需要查找的目录:')
program_dir = os.getcwd()
serach_file(start_dir,target)

f = open(program_dir + os.sep + 'gui1——vedioList.txt','w')
f.writelines(vedio_list)
f.close()

# g.choicebox(msg='在 【%s】 系列路径下工搜索满足条件的文件如下' % start_dir,choices=vedio_list)

g.multchoicebox(msg='在 【%s】 系列路径下工搜索满足条件的文件如下' % start_dir,choices=vedio_list)
# multchoicebox()函数也是提供一个可选择的列表,与choicebox()不同的是,multchoicebox()支持用户选择0个,1个或者同时选择多个选项。

在这里插入图片描述

  1. 编写程序:GUI—— 让用户输入密码进行登录验证(multpasswordbox)。
from easygui import *
msg = "验证登陆信息"
title = "密码函数multpasswordbox示例"
fieldNames = ["服务器 ID", "用户 ID", "密码"]
fieldValues = []  # we start with blanks for the values
fieldValues = multpasswordbox(msg, title, fieldNames)
print("输入的信息是: %s" % str(fieldValues))

在这里插入图片描述
49. 编写程序:GUI—— 提供一个文件夹浏览框让用户选择需要打开的文件(fileopenbox、textbox)。

#提供一个文件夹浏览框,让用户选择需要打开的文件,打开并显示文件内容
import easygui as g
import os

file_path = g.fileopenbox(default="*.txt")

with open(file_path) as f:
    title = os.path.basename(file_path)#os.path.basename(),返回path最后的文件名
    msg = "文件【%s】的内容如下:" % title
    text = f.read()
    g.textbox(msg, title, text)

在这里插入图片描述

  1. 编写程序:GUI—— 提供一个文件夹浏览框让用户选择需要打开的文件,并比较当前文件是否修改过 (fileopenbox、textbox、buttonbox、filesavebox)。
#在提供一个文件夹浏览框让用户选择需要打开的文件的基础上增强功能:当用户点击OK按钮的时候,比较当前文件是否修改过,如果修改过,则提示覆盖保存,放弃保存或另存为并实现相应功能。

import easygui as g
import os

file_path = g.fileopenbox(default='*.txt')

with open(file_path) as old_file:
    title = os.path.basename(file_path)
    msg = '文件【%s】的内容如下:' % title
    text = old_file.read()
    text_after = g.textbox(msg,title,text)#easygui.textbox函数会在返回的字符串后边追加一个行结束符(“\n”),即print一下就能看见后面多了一个\n,
                                          #而没有print出来的但是已经被调用的则是单纯的字符串没有\n,如果要比较字符串是否发生了改变我们需要人工的把这个\n给忽略掉。
                                          #所以说“字符串[-1]”恰好就是这个\n

if text != text_after[:-1]: #textbox的返回值会在末尾追加一个换行符    #os里的read()输出是一个大的字符串,那么这个大的"字符串[:-1]"就是一个仅仅少一个最后一个字符而已
    choice = g.buttonbox('检测到文件内容发生改变,请选择以下操作:','警告',('覆盖保持','放弃保存','另存为...'))
    if choice == '覆盖保存':
        with open(file_path,'w') as old_file:
            old_file.write(text_after[:-1])
    if choice == '放弃保存':
        pass
    if choice == '另存为...':
        another_path = g.filesavebox(default='.txt')
        if os.path.splitext(another_path)[1] != '.txt':
            another_path += '.txt'
        with open(another_path,'w') as new_file:
            new_file.write(text_after[:-1])

在这里插入图片描述

标签:key,Python,50,41,file,each,path,txt,os
来源: https://blog.51cto.com/u_15178976/2790853

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有