初识python之 正则案例:找到记录中所有user_name的值

发布时间 2023-03-27 10:48:02作者: Simple-Sir

数据样例 user_info.txt

user_name={李大牛} age={29} phone_no={13856819955}
user_name={李二牛} age={26} phone_no={13956819955}
phone_no={13256819955} user_name={李四} age={32}
phone_no={13356819955}  age={32} user_name={李四}

需求 

找到记录中所有user_name的值,并写入文件。

写入txt文件

#!/user/bin/env python
#-*-coding:utf-8 -*-
# author:SimpleSir
# create_time:2023/3/23 10:23
import re
from xlsxwriter import Workbook

# 数据样例
# user_name={李二娃} age={30} phone_no={15756819955}

# 需求
# 找到记录中所有user_name的值

# 定义正则匹配规则
r = re.compile(r'''
               user_name={ # 匹配字符串:“user_name={”
               (.*?)}      # 匹配在"user_name={"之后,"}"之前的任意字符,?是只匹配第一次的"}"
               ''',re.VERBOSE)

# 读取文件user_info.txt所有记录
with open('user_info.txt','r',encoding='utf-8') as f:
    lines=f.readlines()

# 通过正则匹配,找到所有user_name,并写入文件userName.txt
with open('userName.txt','w',encoding='utf-8') as f:
    for line in lines:
        ret = re.search(r, line)
        user_name=ret.group(1)
        f.write('%s\n'%(user_name))

# 后面步骤灵活处理,多一种参考。

# 读取userName.txt文件所有记录,剔除换行符,并统计user_name出现的次数
with open('userName.txt','r',encoding='utf-8') as f:
    lines=f.readlines()
count_list={}  # 以字典方式存放数据
for i in lines:
    count_list[i.replace('\n','')]=lines.count(i)

# 把字典内容写入文件 user_name_count.txt
with open('user_name_count.txt','w',encoding='utf-8') as f:
    for k,v in count_list.items():
        f.write('%s\t%s\n'%(k,v))
    f.write('总人数\t'+str(len(count_list)))
写入txt

结果

 

 

写入excel

#!/user/bin/env python
#-*-coding:utf-8 -*-
# author:SimpleSir
# create_time:2023/3/23 10:23
import re
from xlsxwriter import Workbook

# 数据样例
# user_name={李二娃} age={30} phone_no={15756819955}

# 需求
# 找到记录中所有user_name的值

# 定义正则匹配规则
r = re.compile(r'''
               user_name={ # 匹配字符串:“user_name={”
               (.*?)}      # 匹配在"user_name={"之后,"}"之前的任意字符,?是只匹配第一次的"}"
               ''',re.VERBOSE)

# 定义表格样式
# 表头格式
title_format = {
        'border': 1,
        'font_name': '微软雅黑',  # 字体
        'font_size': 10,  # 字体大小
        'font_color': 'black',  # 字体颜色
        'bold': True,  # 是否粗体
        'align': 'center',  # 水平居中对齐
        'valign': 'vcenter',  # 垂直居中对齐
        'bg_color':'#A9A9A9'
    }
# 数据格式
data_format = {
        'border': 1,
        'font_name': '微软雅黑',  # 字体
        'font_size': 10,  # 字体大小
        'font_color': 'black',  # 字体颜色
        'align': 'center',  # 水平居中对齐
        'valign': 'vcenter'  # 垂直居中对齐
    }

xls = Workbook('result.xlsx') # 创建excel文件
sheet=xls.add_worksheet('用户量')  # 添加sheet
sheet.set_column('A:A',10) # 设置列宽
sheet.write(0, 0,'user_name',xls.add_format(title_format))  # 添加表头

# 读取文件user_info.txt所有记录,通过正则匹配,找到所有user_name,并写入文件result.xlsx
with open('user_info.txt','r',encoding='utf-8') as f:
    line=f.readlines()
for n,u in enumerate(line):
    ret = re.search(r, u)
    user_name=ret.group(1)
    sheet.write(n+1, 0, user_name, xls.add_format(data_format))  # 写入数据
xls.close()
写入excel

结果