re.sub 指定位置插入

本文详细介绍了正则表达式中group()函数的使用方法,包括如何通过group(0), group(1)等获取匹配的字符串部分。同时,解释了re.sub函数中特殊字符1的作用,帮助读者更好地理解并运用正则表达式的分组功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先说下group()

group() 用来提出分组截获的字符串,举个例子:

- group(0)就是匹配正则表达式整体结果

- group(1) 列出第一个括号匹配部分,group(2) 列出第二个括号匹配部分,group(3) 列出第三个括号匹配部分。

re.sub

其中“\1”表示括号内的部分

怎么打包这个import os import tkinter as tk from tkinter import filedialog from openpyxl import load_workbook from tkinterdnd2 import DND_FILES, TkinterDnD import warnings import re from docx import Document from docx.oxml.shared import qn from docx.oxml import parse_xml import xml.etree.ElementTree as ET from zipfile import ZipFile import tempfile import shutil warnings.filterwarnings("ignore", category=UserWarning, module="openpyxl.reader.drawings") def replace_in_xlsx(file_path, old_text, new_text): wb = load_workbook(file_path) for sheet in wb.sheetnames: ws = wb[sheet] for row in ws.iter_rows(): for cell in row: if isinstance(cell.value, str) and old_text in cell.value: cell.value = cell.value.replace(old_text, new_text) wb.save(file_path) def replace_in_docx(file_path, old_text, new_text): """ 全面替换Word文档中所有位置指定文本(包括图表、批注等) 返回处理后的文件路径(避免直接覆盖原文件) """ # 创建临时副本防止原文件锁定 temp_dir = tempfile.mkdtemp() temp_file = os.path.join(temp_dir, "temp.docx") shutil.copyfile(file_path, temp_file) try: # 第一阶段:使用python-docx处理常规内容 doc = Document(temp_file) pattern = re.compile(re.escape(old_text), re.IGNORECASE) # 1. 处理段落(合并Run后替换) for para in doc.paragraphs: full_text = ''.join([run.text for run in para.runs]) if pattern.search(full_text): # 清空所有Run for run in para.runs: run.text = '' # 在第一个Run插入新文本 if para.runs: para.runs[0].text = pattern.sub(new_text, full_text) else: para.add_run(pattern.sub(new_text, full_text)) # 2. 处理表格(含嵌套表格) def process_table(table): for row in table.rows: for cell in row.cells: for para in cell.paragraphs: full_text = ''.join([run.text for run in para.runs]
03-26
import os import re #re正则库 #定义获取index.html时间函数 def get_time_from_index_html(directory): #拼接指定目录的上一级目录 index_html_path = os.path.join(directory,"..","index.html") #打开index文件存到f变量里,read读取内容返回给content with open(index_html_path,"r",encoding="utf-8") as f: content = f.read() #正则查找index文件开始时间和结束时间 #.任意除了换行符\n之外任意单个字符,*匹配前面字符一次或多次,?非贪婪模式,如果多个相同的尽量匹配少的 start_time_match = re.search(r"开始:(.*?)<br />",content) end_time_match = re.search(r"结束:(.*?)</td>",content) #group(1)返回匹配到的捕获组(第一个括号里的正则),返回两个时间的元组 if start_time_match and end_time_match: start_time = start_time_match.group(1) end_time = end_time_match.group(1) return start_time , end_time else: return None, None #定义时间替换函数 def replace_html_time(directory): #获取时间元组 start_time, end_time = get_time_from_index_html(directory) if start_time is None or end_time is None: print("无法提取起始时间和结束时间") return #os.walk 函数遍历指定目录 directory 中的所有文件和子目录。 #os.walk 函数返回一个生成器(Generator),用于递归地遍历指定目录下的文件和子目录。它返回的三个值 root、dirs 和 files 分别表示当前遍历到的目录路径、子目录列表和文件列表。 for root, dirs, files in os.walk(directory): for file in files: #遍历所有html结尾的文件 if file.endswith(".html"): #拼接文件完整路径,只读(r)打开文件,文件对象f调用read方法读取文件内容并赋给变量content file_path = os.path.join(root, file) with open(file_path,"r",encoding="utf-8") as f: content = f.read() #正则匹配遍历的文件替换index文件的时间存给变量content #sub方法替换,r原始字符串,f格式化字符串,可以插入变量 content = re.sub(r"<th>扫描起始时间</th>\n\t\t\t\t<td>.*?</td>",f"<th>扫描起始时间</th>\n\t\t\t\t<td>{start_time}</td>",content) content = re.sub(r"<th>扫描结束时间</th>\n\t\t\t\t<td>.*?</td>",f"<th>扫描结束时间</th>\n\t\t\t\t<td>{end_time}</td>",content) #写入模式打开文件,write方法替换修改后的内容 with open(file_path,"w",encoding="utf-8") as f: f.write(content) print(f"已替换文件:{file_path}") #指定的目录 directory_path = "" replace_html_time(directory_path) 修改代码为修改host文件下所有文件格式为x.x.x.x.html文件的扫描起始时间和扫描结束时间,-r 扫描起始时间,-f 扫描结束时间,为传入参数
最新发布
07-31
import os from bs4 import BeautifulSoup import re 指定文件夹路径 folder_path = "C:/Users/test/Desktop/DIDItest" 正则表达式模式 pattern = r'<body>(.*?)</body>' 遍历文件夹中的所有文件 for root, dirs, files in os.walk(folder_path): for file in files: # 读取html文件 file_path = os.path.join(root, file) with open(file_path, "r", encoding="utf-8-sig") as f: html_code = f.read() # 创建BeautifulSoup对象 soup = BeautifulSoup(html_code, 'html.parser') # 使用正则表达式匹配<body>标签内的数据 body_data = re.findall(pattern, html_code, re.DOTALL) # 剔除<p>和()</p> body_data = body_data[0].replace("<p>", "").replace("()</p>", "") # 使用正则表达式提取talk_id、时间、发送者ID和接收者ID matches = re.findall(r'\[talkid:(\d+)\](\d+年\d+月\d+日 \d+:\d+:\d+).*?<span.*?>(\d+)<.*?>(.*?)<.*?''((中发言|发送)\s(.*?)\s)', body_data) # 提取唯一ID,时间,发送号码和私聊群聊关键词 matches1 = re.findall(r'<span.*?hint-success.*?>(\d+)', body_data) matches2 = re.findall(r'(?:中发言|发送)\s*(.*?)\s*(?:音频 :|图片 :)?(?:\[([^\]]+)\])?', body_data) # 处理匹配结果 for match in matches: talk_id = match[0] time = match[1] send_id = match[2] talk_type = match[3] content = match[4] # 提取第二个号码为接收号码 if len(matches1) >= 2: receive_id = matches1[3] # 替换字符 time = time.replace('年', '-').replace('月', '-').replace('日', '') talk_type = talk_type.replace('向', '私聊').replace('在群', '群聊') content = content.replace('音频', '').replace('图片', '').replace('发送','').replace('中发言','') content = re.sub(r'\n', '', content) print("---导入完成-----") 使用python 创建sql数据库并将数据导入到sql文件中
07-17
import os from bs4 import BeautifulSoup import re 指定文件夹路径 folder_path = "C:/Users/test/Desktop/DIDItest" 正则表达式模式 pattern = r'<body>(.*?)</body>' 遍历文件夹中的所有文件 for root, dirs, files in os.walk(folder_path): for file in files: # 读取html文件 file_path = os.path.join(root, file) with open(file_path, "r", encoding="utf-8-sig") as f: html_code = f.read() # 创建BeautifulSoup对象 soup = BeautifulSoup(html_code, 'html.parser') # 使用正则表达式匹配<body>标签内的数据 body_data = re.findall(pattern, html_code, re.DOTALL) # 剔除<p>和()</p> body_data = body_data[0].replace("<p>", "").replace("()</p>", "") # 使用正则表达式提取talk_id、时间、发送者ID和接收者ID matches = re.findall(r'\[talkid:(\d+)\](\d+年\d+月\d+日 \d+:\d+:\d+).*?<span.*?>(\d+)<.*?>(.*?)<.*?''((中发言|发送)\s(.*?)\s)', body_data) # 提取唯一ID,时间,发送号码和私聊群聊关键词 matches1 = re.findall(r'<span.*?hint-success.*?>(\d+)', body_data) matches2 = re.findall(r'(?:中发言|发送)\s*(.*?)\s*(?:音频 :|图片 :)?(?:\[([^\]]+)\])?', body_data) # 处理匹配结果 for match in matches: talk_id = match[0] time = match[1] send_id = match[2] talk_type = match[3] content = match[4] # 提取第二个号码为接收号码 if len(matches1) >= 2: receive_id = matches1[3] # 替换字符 time = time.replace('年', '-').replace('月', '-').replace('日', '') talk_type = talk_type.replace('向', '私聊').replace('在群', '群聊') content = content.replace('音频', '').replace('图片', '').replace('发送','').replace('中发言','') content = re.sub(r'\n', '', content) print("---导入完成-----") 创建sql数据库并将数据导入到sql文件中
07-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值