matches = re.findall(pattern, content)
时间: 2024-05-23 18:14:04 浏览: 15
这是一个使用 Python 中 re 模块进行正则表达式匹配的代码片段。re 模块提供了一些函数来进行正则表达式的匹配操作,其中最常用的函数是 findall()。这个函数接受两个参数:正则表达式模式和需要匹配的字符串。它会返回一个列表,其中包含了所有匹配到的字符串。在这个代码片段中,我们使用了变量名 matches 来存储所有匹配到的字符串。
相关问题
response = requests.get(url, params=data) print(response.text) response_text = response.text.encode("utf8").decode('unicode_escape') pattern = r'"data":\s*{\s*"text":\s*"([^"]*)"' matches = re.findall(pattern, response_text)
这段代码使用了`requests`库发送了一个GET请求到指定的URL,并且传递了一个名为`data`的参数。在这个例子中,`data`是一个字典,其中包含了两个键值对:`"token"`和`"content"`。
接下来,通过调用`response.text`获取了API的响应内容,并将其打印出来。然后,对响应内容进行了编码和解码的操作,将其从UTF-8编码转换为Unicode字符串。
然后,使用正则表达式模式`r'"data":\s*{\s*"text":\s*"([^"]*)"'`来匹配响应内容中的特定文本。这个模式的含义是匹配以`"data": {"text": "`开头,以`"`结尾的文本,并且提取其中的内容。
最后,使用`re.findall()`函数在响应内容中应用正则表达式模式,并将匹配到的结果存储在`matches`变量中。
总结来说,这段代码的目的是发送一个API请求,获取响应并从中提取出特定的文本内容。
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") as f: html_code = f.read() # 使用正则表达式匹配<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+)<.*?>(.*?)<', body_data) # 提取唯一ID,时间,发送号码和私聊群聊关键词 matches1 = re.findall(r'<span.*?hint-success.*?>(\d+)<.*?>', body_data) # match = re.search('(中发言|发送)\s(.*?)\s', body_data) # if match: # content = match.group(2) matches2 = re.findall('(中发言|发送)\s(.*?)\s', body_data) for match in matches2: content = match[1] soup = BeautifulSoup(content, 'html.parser') if soup.find('<a href'): content = '' # 提取第二个号码为接收号码 if len(matches1) >= 2: receive_id = matches1[3] # 处理匹配结果 for match in matches: talk_id = match[0] time = match[1] send_id = match[2] talk_type = match[3] # 进行时间格式转换,将time转换为"0000-00-00"格式 time = time.replace('年', '-').replace('月', '-').replace('日', '') talk_type = talk_type.replace('向', '私聊').replace('在群', '群聊') # 打印结果 print("Talk ID:", talk_id) print("Time:", time) print("Sender ID:", send_id) print("Receive_id:", receive_id) print("Talk_type:", talk_type) print("Content:",content) print("---")导入至csv
要将提取的信息导入 CSV 文件,你可以使用 Python 的 CSV 模块。下面是一个示例代码,可以帮助你实现这个需求:
```python
import os
import csv
from bs4 import BeautifulSoup
import re
folder_path = "C:/Users/test/Desktop/DIDItest"
output_file = "output.csv"
# 正则表达式模式
pattern = r'<body>(.*?)<\/body>'
# 创建 CSV 文件并写入表头
with open(output_file, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["Talk ID", "Time", "Sender ID", "Receiver ID", "Talk Type", "Content"])
# 遍历文件夹中的所有文件
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
# 读取 HTML 文件
with open(file_path, "r", encoding="utf-8") as html_file:
html_code = html_file.read()
# 使用正则表达式匹配<body>标签内的数据
body_data = re.findall(pattern, html_code, re.DOTALL)
if body_data:
# 剔除<p>和()</p>
body_data = body_data[0].replace("<p>", "").replace("()</p>", "")
# 使用正则表达式提取信息
matches = re.findall(r'\[talkid:(\d+)\](\d+年\d+月\d+日 \d+:\d+:\d+).*?<span.*?>(\d+)<.*?>(.*?)<', body_data)
matches1 = re.findall(r'<span.*?hint-success.*?>(\d+)<.*?>', body_data)
matches2 = re.findall('(中发言|发送)\s(.*?)\s', body_data)
if len(matches1) >= 2:
receive_id = matches1[1]
# 处理匹配结果
for match in matches:
talk_id = match[0]
time = match[1]
send_id = match[2]
talk_type = match[3]
# 进行时间格式转换
time = time.replace('年', '-').replace('月', '-').replace('日', '')
talk_type = talk_type.replace('向', '私聊').replace('在群', '群聊')
# 处理内容
content = ""
for match in matches2:
content = match[1]
soup = BeautifulSoup(content, 'html.parser')
if soup.find('a'):
content = ""
break
# 写入 CSV 文件
writer.writerow([talk_id, time, send_id, receive_id, talk_type, content])
```
这段代码将提取的信息写入名为 "output.csv" 的 CSV 文件中。你可以根据需要修改输出文件的路径和名称。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
from bs4 import BeautifulSoup import csv import os import re # 设置文件夹路径 folder_path = 'C:/Users/test/Desktop/DIDItest' # 创建CSV文件 csv_file = open('output.csv', 'w', newline='') csv_writer = csv.writer(csv_file) csv_writer.writerow(['ID', '时间', '发送号码', '接收号码', '发送内容']) # 遍历文件夹下的所有文件 for root, dirs, files in os.walk(folder_path): for file in files: if file.endswith('.html'): file_path = os.path.join(root, file) # 打开文件并解析HTML源代码 with open(file_path, 'r', encoding='utf-8') as f: soup = BeautifulSoup(f, 'html.parser') # 提取talkid、时间、发送号码、接收号码、信息类型和消息内容的正则表达式模式 pattern = r'\[talkid:(\d+)\](.*?) 向 (.*?) 发送 (.*?):\[(.*?)\]' matches = re.findall(pattern, soup) # 遍历匹配结果并输出 for match in matches: talkid = match[0] time = match[1].strip() sender = match[2].strip() receiver = match[3].strip() type = match[4].strip() content = re.findall(r'', match[5])[0] if type in ['音频', '图片'] else match[5] # 写入CSV文件 csv_writer.writerow([talkid, time, sender, receiver, content]) # 关闭CSV文件 csv_file.close() print("数据已成功写入CSV文件。")
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
import re html = ''' <html> <meta http-equiv="Content=-Type" content="text/html; charset=utf-8"/> <head> </head> <body>[talkid:137031381]2014年4月20日 03:55:45 , 2323234 在群 20011 中发言 我们已经是dffwerwer天吧! [talkid:137031382]2014年4月22日 04:45:45 , 2323234 在群 20011 中发言 音频 :[音频 [talkid:137031383]2014年4月23日 04:55:45 , 2323234 在群 20011 中发言 图片 :[图片 [talkid:137031384]2014年4月24日 05:55:45 , 2323234 在群 20011 中发言 我们已方式方法方式 [talkid:137031385]2014年4月25日 06:55:45 , 2323234 在群 20011 中发言 我而对方是否的天吧! </body> </html> ''' pattern = r'\(发送|中发言)\s*(.*?).*?(音频 :|图片 :).*?(\[.*?\])' matches = re.findall(pattern, html, re.DOTALL) for match in matches: content= match[0] content_type = match[1] file_link = match[2] if content_type == '音频 :': print(f"音频链接地址: {file_link}") elif content_type == '图片 :': print(f"图片链接地址: {file_link}") else: print(f"发言字段: {content}")
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)