鱼C论坛

 找回密码
 立即注册
12
返回列表 发新帖
楼主: HL1

[学习笔记] python学习记录

[复制链接]
 楼主| 发表于 2018-8-21 19:29:07 | 显示全部楼层
19.打印一定区间的行
def open_file():
    file_name = input('请输入要打开的文件名:')
    str1 = input('请输入需要显示的行数【格式如13:21】:')
    l = str1.split(':') #分裂输入的参数
    count1 = int(l[0])   #分别将其转换为整型
    count2 = int(l[1])
    count = 1
    f = open(file_name)

    while True:
        line = f.readline()
        if count >= count1:
            print(line,end='')
        count += 1
        if count > count2:
            break

    f.close()
open_file()
注意count += 1的位置
没有考虑发哦不输入数字的情况,如:32
print中如果没有end=''打印间距比较大,why? 百度说这样print在末尾添加一个换行符,而是添加一个空格字符结尾
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-21 20:35:15 | 显示全部楼层
20.替换
def open_file():
    file_name = input('请输入文件名:')
    str1 = input('请输入需要替换的单词或字符:')
    str2 = input('请输入新的单词或字符:')
    f = open(file_name,'+r')
    list1 = []
    count = 0

    for eachline in f:
        list1.append(eachline)
    for i in range(len(list1)):
        if str1 in list1[i]:
            count += 1
    if count == 0:
        print('不存在')
    else:
        print('文件中共有%s个【%s】' % (count, str1))
        m = input('你确定要把所有的【%s】替换为【%s】吗?\n【YES/NO】:' % (str1,str2))
        if m.lower() == 'yes':
            for i in range(len(list1)):
                if str1 in list1[i]:
                    list1[i].replace(str1,str2)
                f.writelines(list1)

    f.close()
open_file()
感觉不知道错在哪里了,郁闷
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-21 20:56:11 | 显示全部楼层

这个题花了好长时间

20.接上
def file_replace(file_name, rep_word, new_word):
    f_read = open(file_name)

    content = []
    count = 0

    for eachline in f_read:
        if rep_word in eachline:
            count += eachline.count(rep_word)
            eachline = eachline.replace(rep_word, new_word)
        content.append(eachline)

    decide = input('\n文件%s中共有%s个【%s】\n你确定要把所有的【%s】替换为【%s】吗?\n【YES/NO】:' % (file_name, count, rep_word, rep_word, new_word))

    if decide in ['YES','Yes','yes']:
        f_write = open(file_name,'w')
        f_write.writelines(content)
        f_write.close()

file_name = input('请输入文件名:')
rep_word = input('请输入需要替换的单词或字符:')
new_word = input('请输入新的单词或字符:')
file_replace(file_name, rep_word, new_word)
参考小甲鱼老师的答案,先打开文件的时候不需要写入,打开和写入分开操作,答案中count后面应该是漏了个加号
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-21 21:03:47 | 显示全部楼层
write一般是写入字符串
writelines是写入列表等可迭代的数据
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-21 22:40:01 | 显示全部楼层
21.统计当前目录下文件的类型及个数
import os
print(os.listdir('.'))
list1 = os.listdir('.')
print(list1)
dict1 = {}
for i in range(len(list1)):
    if '.' in list1[i]:
        m, n = list1[i].split('.')
        n = '.' + n
        if n in dict1:
            dict1[n] += 1
        else:
            dict1[n] = 1
    else:
        if '文件夹' in dict1:
            dict1['文件夹'] += 1
        else:
            dict1['文件夹'] = 1
for k,v in dict1.items():
    print('该文件夹下共有类型为【%s】的文件%s个' % (k,v))
print(dict1)
os.listdir()列举路径下的所有文件(返回的是一个列表),文件夹没有后缀
import os

all_files = os.listdir(os.curdir)
type_dict = dict()

for each_file in all_files:
    if os.path.isdir(each_file):
        type_dict.setdefault('文件夹', 0)
        type_dict['文件夹'] += 1
    else:
        ext = os.path.splitext(each_file)[1]
        type_dict.setdefault(ext, 0)
        type_dict[ext] += 1
for k,v in type_dict.items():
    print('该文件夹下共有类型为【%s】的文件%s个' % (k,v))
print(type_dict)
参考小甲鱼老师的答案,比我的多用了os.path.isdir()判断路径是否存在且是一个目录,还有os.path.splitext()分割文件名与扩展名返回元组,后面[1]是取扩展名,不用像我一样还有自己加点'.',还有字典的setdefault方法,如果字典中包含该键,则返回该键的值(我理解就是不做任何操作),如果不包含则添加该key并设置其值value,用这个不用另外添加if判断语句
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-21 22:48:06 | 显示全部楼层
本帖最后由 HL1 于 2018-8-21 22:52 编辑

22.计算目录下个文件的大小
import os

all_files = os.listdir(os.curdir)
file_dict = dict()

for each_file in all_files:
    file_dict.setdefault(each_file, os.path.getsize(each_file))


for k,v in file_dict.items():
    print('%s【%sBytes】' % (k,v))
print(file_dict)
完成上一题后感觉这一题比较简单

看了小甲鱼老师的答案,j加了用os.path.isfile()判断路径是否存在且是是一个文件(就是判断是不是文件),只统计文件,过滤掉文件夹
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-22 00:20:13 | 显示全部楼层
23.搜索路径下的文件
import os

def seek(p):
    list1 = os.listdir(p)
    print(list1)
   
#判断目录中是否存在文件夹
    for i in range(len(list1)):
        if '.' not in list1[i]:
            p = p+'\\'+list1[i]
            return seek(p)
        elif file_name == list1[i]:
            print(p+'\\'+file_name)
   
p = input('请输入待查找的初始目录:')
file_name = input('请输入需要查找的目标文件:')
seek(p)
不知道哪个地方出问题了  汗
看答案修改后
import os

def seek_file(p, file_name):
    os.chdir(p)

    for each_file in os.listdir(os.curdir):
        if each_file == file_name:
            print(os.getcwd() + os.sep + each_file)
        if os.path.isdir(each_file):
            seek_file(each_file, file_name)
            os.chdir(os.pardir)

p = input('请输入待查找的初始目录:')
file_name = input('请输入需要查找的目标文件:')
seek_file(p,file_name)
之前的错误应该是递归后没有返回上一层目录
os.listdir()列举
os.chdir()改变工作目录(我的理解是并非修改目录,而是“下面的操作””移动到该目录下)
os.getcwd()返回当前目录(返回的值是当前的目录)
os.sep路径分隔符,,比'\\'高大上多了
os.pardir()指上一级目录
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-22 00:28:02 | 显示全部楼层
HL1 发表于 2018-8-22 00:20
23.搜索路径下的文件
import os

如果将os.getcwd()改为os.curdir虽然不会出错,但是输出结果为点‘.’
如果将os.getcwd()改为p也不会出错,但是这样输出的只是目标文件所在的目录,上一级上上一级的没有输出
os.curdir不能改为p否则会出错,这点不太懂???     但是可以改为os.getcwd()
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-22 23:59:52 | 显示全部楼层
24.寻找视频文件
import os

def seek(p):
    os.chdir(p)
    list1 = ['.mp4', '.rmvb', '.avi']
    list2 = []

    for each_file in os.listdir(os.curdir):
        if os.path.isfile(each_file):
            if os.path.splitext(each_file)[1] in list1:
                list2.append(os.getcwd() + os.sep + each_file)

    f = open('vedioList.txt','a')
    f.writelines(list2)
    f.close()
    for each_file in os.listdir(os.curdir):
        if os.path.isdir(each_file):
            seek(each_file)
            os.chdir(os.pardir)


p = input('请输入待查找的初始目录:')
seek(p)
  又有错误
原来是访问E盘被拒绝了,小甲鱼老师的答案也是:另外最大的问题是list空白不要放在迭代函数中,为了不使list被迭代时初始化为空列表我还把文件的读取写入放在函数中了,还多搞了一个for循环(为了区分文件和文件夹迭代方便写入),真是为了弥补一个缺点又造成了一个问题  这样运行的结果就是在每一个文件里创建一个vedioList.txt了(算意外收获吗),另外还有速度慢,说明自己对文件路径这一块理解还不够啊
import os

def search_file(start_dir):
    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):
            search_file(each_file, target)
            os.chdir(os.pardir)

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

target = ['.txt', '.py',]
vedio_list = []


search_file(start_dir, target)

f = open(program_dir + os.sep + 'vedioList.txt', 'w')
f.writelines(vedio_list,)
f.close()
小甲鱼老师的答案很规范要多学习学习,一定要注意不要随便把东西放入迭代函数中,一定一定要注意
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-8-23 00:27:32 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2018-8-25 19:31:06 | 显示全部楼层
25.查找txt文件中的关键字,并输出
encoding = 'UTF-8'
import os

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:
        pos.append(begin + 1)
        begin = line.find(key, begin + 1)

    return pos

def search_in_file(file_name, key):
    f = open(file_name)
    count = 0
    key_dict = dict()

    for each_line in f:
        count += 1
        if key in each_line:
            pos = pos_in_line(each_line, key)
            key_dict[count] = pos

    f.close()
    return key_dict

def search_file(key, detail):
    all_files = os.walk(os.getcwd())
    txt_files = []

    for i in all_files:
        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)
               
    for each_txt_file in txt_files:
        key_dict = search_in_file(each_txt_file, key)
        if key_dict:
            print('======================================================')
            print('在文件【%s】中找到关键字【%s】' % (each_txt_file, file))
            if detail in ['YES', 'yes', 'Yes']:
                print_pos(key_dict)

key = input('请将该代码放于待查找的文件夹内,请输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
search_file(key, detail)
加了UTF-8都不行,郁闷
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-25 21:50:38 | 显示全部楼层
26.raise语句
try:
    for i in range(3):
        for j in range(3):
           if i == 2:
                raise KeyboardInterrupt
                print(i, j)
except KeyboardInterrupt:
    print('出错了')
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-25 22:18:54 | 显示全部楼层
27.创建函数判断是否是整数:
def int_input(prompt=''):
    while True:
        try:
             int(input(prompt))
        excecpt ValueError:
             print('输入的不是整数!')
int_input('请输入一个整数:')
原来输入小数后不能再转化为整数了,那么问题来了,如何将一个输入的小数转化为整数呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-25 22:22:38 | 显示全部楼层
HL1 发表于 2018-8-25 22:18
27.创建函数判断是否是整数:
def int_input(prompt=''):
    while True:

太笨了,将int改为float即可
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-10-3 14:51:00 | 显示全部楼层
28. 编写程序,用pickle将文件(record.txt)里的对话腌制成不同的文件
import pickle

def save_file(boy, girl, count):
    file_name_boy = 'boy_' + str(count) + '.txt'
    file_name_girl =  'girl_'  + str(count) + '.txt'

    boy_file = open (file_name_boy, 'wb')
    girl_file = open (file_name_girl, 'wb')

    pickle.dump(boy, boy_file)
    pickle.dump(girl,  girl_fille)
     
    boy_file.close()
    girl_file.close()

def split_file(file_name):
    count = 1
    boy = []
    girl = []

    f = open(file_name)
   
    for each_line in f:
        if each_line[:6] != '======':
            (role, line_spoken = each_line.splite(':', 1))
             if  role == '小甲鱼':
                   boy.append(line_spoken)
             if role == '小客服':
                   girl.append(line_spoken)
         else:
              save_file(boy, girl,count)
               boy = []
               girl = []
               count += 1
         
          save_file(boy, girl, count)
          f.close()

split_file('record.txt')
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-10-3 16:39:03 | 显示全部楼层
第34讲,测试题第5题
with A() as a:
    with B() as b:
        suite
可以写为
with A() as a, B() as b:
    suite
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 14:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表