013 Python语法之文件与生成器

1. itertools 生成器工具类

product 函数
import itertools

it = itertools.product("0123",repeat=16)
product 函数参数介绍
  1. 第一个参数是元素的列表
  2. 第二个参数是每个字符可重复的次数
  3. 返回值 it 是总共可生成元素个数的repeat次方个的排列的元素的序列(也可看做迭代器)
product 函数例子
it = itertools.product("01",repeat=2)
for i in it:
    print("我是数据:" + i)

# 打印出数据
我是数据:00
我是数据:01
我是数据:10
我是数据:11

2. join 函数

"x".join("123")  --> 1x2x3
join 函数参数详解
  1. 前面.调用它的是一个字符串
  2. 参数是原始的字符串
  3. 返回值是进行join操作后的字符串
join 函数例子
str1 = "x".join("123")
print("打印结果:", str1)
# 打印结果
打印结果:1x2x3

3. 综合案例1(账号,密码,邮箱分类)

# 1. 路径(模板)
csdnPath = r"F:\yinchengDay2Down\csdn.txt"      # r 是为了不加\\
csdnPwdPath = r"F:\csdn\csdnPwd.txt"
csdnUserPath = r"F:\csdn\csdnUser.txt"
csdnEMailPath = r"F:\csdn\csdnEmail.txt"

# 2. 文件(模板)
csdnFile = open(csdnPath, "r", errors="ignore")     # 如果是“r”模式,一定要有这个文件   errors="ignore"是为了忽略打开文件时候的错误
csdnPwdFile = open(csdnPwdPath, "w")        # w 覆盖写入
csdnUserFile = open(csdnUserPath, "w")
csdnEMailFile = open(csdnEMailPath, "w")

print("写入开始!")

# 3. 硬盘循环读取每一行数据,并处理
while True:
    # 1. 读一行
    line = csdnFile.readline()

    # 2. 判断是否到末尾
    if not line:    # 如果到文件末尾返回None
        break

    # 3. 每一行的处理
    lineList = line.split(" # ")

    # 4. 写该行数据到对应文件中
    csdnUserFile.write(lineList[0] + "\n")
    csdnPwdFile.write(lineList[1] + "\n")
    csdnEMailFile.write(lineList[2])

print("写入完毕!")

# 4. 关闭文件(模板)   一定要关闭
csdnFile.close()
csdnUserFile.close()
csdnPwdFile.close()
csdnEMailFile.close()

4. 综合案例2(密码次数概率统计)

# 1. 路径
csdnPwdPath = r"F:\csdn\csdnPwd.txt"  # 源文件路径
csdnPwdCountPath = r"F:\csdn\csdnPwdCount.txt"  # 目标路径

# 2. 文件
csdnPwdFile = open(csdnPwdPath, "r", errors="ignore")  # 源文件
csdnPwdCountFile = open(csdnPwdCountPath, "w")  # 目标文件

# 3. 内存模式读取源文件并处理
print("读取开始!")
lineList = csdnPwdFile.readlines()  # 源文件全部读取到列表中
print("读取完成!")

print("密码排序开始!")
lineList.sort()  # 对密码进行排序,方便重复的密码个数进行相加
print("密码排序结束!")

print("次数排序开始!")
count = 1  # 统计单个密码重复的个数
list1 = []  # 二维列表,存储 【[相同密码的个数,密码],...】

# 循环读取排序后的每一个密码
for index in range(1, len(lineList)):
    # 比较前后两个密码是否相同
    if lineList[index - 1] == lineList[index]:
        # 如果相同,次数加1
        count += 1
    else:  # 如果前后两个元素不相同,那么就把前面count加过的相同进行加入到list1中
        list1.append([count, lineList[index - 1]])
        count = 1  # 计数初始化,一定要加上

list1.append([count, lineList[-1]])  # 一定要加上,这个是用来将最后一个元素加进去的

list1.sort(key=lambda x: x[0])  # 利用lambda表达式进行
list1.reverse()
print("次数排序结束!")

print("写入开始!")
for line in list1:
    csdnPwdCountFile.write(str(line[0]) + " # " + line[1])
print("写入结束!")

# 4. 关闭
csdnPwdFile.close()
csdnPwdCountFile.close()

进步,加油。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值