import os import re from bs4 import BeautifulSoup # 指定文件夹路径 folder_path = "C:/Users/test/Desktop/DIDItest" # 遍历文件夹中的所有文件 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() # 创建BeautifulSoup对象 soup = BeautifulSoup(html_code, 'html.parser')提取发送或发言的字符串

时间: 2024-04-16 07:29:26 浏览: 19
根据你提供的代码,你想遍历指定文件中的所有 HTML 文件,并使用 BeautifulSoup 提取其中包含 "发送" 或 "发言" 的字符串。 你可以使用 BeautifulSoup 的 `find_all()` 方法结合正则表达式来匹配包含特定字符串的文本内容。下面是一个示例代码,展示了如何修改你的代码来实现这一目标: ```python import os import re from bs4 import BeautifulSoup # 指定文件夹路径 folder_path = "C:/Users/test/Desktop/DIDItest" # 遍历文件夹中的所有文件 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() # 创建BeautifulSoup对象 soup = BeautifulSoup(html_code, 'html.parser') # 使用正则表达式匹配包含 "发送" 或 "发言" 的文本内容 pattern = re.compile("(发送|发言)") matched_strings = soup.find_all(text=pattern) # 打印匹配到的字符串 for string in matched_strings: print(string) ``` 在上面的代码中,我们使用正则表达式 `(发送|发言)` 来匹配包含 "发送" 或 "发言" 的文本内容。然后,我们使用 `find_all()` 方法根据这个正则表达式模式找到所有匹配的结果,并将它们存储在 `matched_strings` 列表中。最后,我们遍历这个列表并打印出每个匹配到的字符串。 请注意,在使用正则表达式时,确保你的模式与实际文本内容匹配。如果没有找到匹配的结果,`matched_strings` 列表将是一个空列表。 希望这可以满足你的需求!如果你还有其他问题,请随时提问。

相关推荐

import os import sqlite3 from bs4 import BeautifulSoup import re # 指定文件夹路径 folder_path = "C:/Users/test/Desktop/DIDItest" # 正则表达式模式 pattern = r'<body>(.*?)</body>' # 连接数据库 conn = sqlite3.connect('chat_data.db') cursor = conn.cursor() # 添加新的字段 cursor.execute("ALTER TABLE DIDI_talk ADD COLUMN file_name TEXT") # 遍历文件夹中的所有文件 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) # 剔除和() body_data = body_data[0].replace("", "").replace("()", "") # # 使用正则表达式提取链接地址 matches2 = re.findall(r'(?:中发言|发送)\s*(.*?)\s*(?:音频 :|图片 :)?(?:\[([^\]]+)\])?', body_data) for match in matches2: # 提取链接地址 file_text = match[1] matches = re.findall(r'"([^"]*)"', file_text) if matches: file_name = matches[0] else: file_name = "No matches found." # 替换字符 file_name = file_name.replace('No matches found.', '') new_data = [file_name] # 更新数据库中新字段的数据 for i, data in enumerate(new_data): cursor.execute("UPDATE DIDI_talk SET file_name = ? WHERE talk_id = ?", (data, i + 1)) # # 处理匹配结果并更新数据库 # for i, match in enumerate(matches): # file_name = matches[0] # new_column_data = new_data[i] # 根据匹配的索引获取对应的新数据 # 提交事务并关闭连接 conn.commit() conn.close() print("---新列数据已添加到数据库中---")

import os import re from bs4 import BeautifulSoup # 设置html文件路径 folder_path = r'C:\Users\test\Desktop\DIDItest' # 提取html文件内所需要数据 def extract_html_info(file_path): with open(file_path, 'r', encoding='utf-8') as file: # 读取HTML源代码 html = file.read() soup = BeautifulSoup(html, 'html.parser') # 提取所有的标签 p_tags = soup.find_all('p') for p_tag in p_tags: # 提取ID talk_id = p_tag.find_previous(string=lambda text: isinstance(text, str) and '[talkid:' in text) talk_id = talk_id.strip('[talkid:]') # 提取时间 timestamp = p_tag.find_previous('body').find_previous('head').find('meta', {'http-equiv': 'Content=-Type'})[ 'content'] # 提取发送号码 send_number = p_tag.find('span', {'class': 'hint-success'}).text # 提取接收号码 receive_number = p_tag.find_all('span', {'class': 'hint-success'})[1].text # 提取信息内容 message = p_tag.previous_sibling.strip() # 遍历文件夹及子文件夹,提取HTML文件信息 for root, dirs, files in os.walk(folder_path): for file in files: if file.endswith('.html'): file_path = os.path.join(root, file) extract_html_info(file_path) # 判断是否是音频 if '音频' in message: file_url = p_tag.find('a')['href'] print( f"ID: {talk_id}, 时间: {timestamp}, 发送号码: {send_number}, 接收号码: {receive_number}, 音频文件地址: {file_url}") else: print( f"ID: {talk_id}, 时间: {timestamp}, 发送号码: {send_number}, 接收号码: {receive_number}, 信息内容: {message}")

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) # 剔除和() body_data = body_data[0].replace("", "").replace("()", "") # 使用正则表达式提取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文件中

import os import re import csv from bs4 import BeautifulSoup # 设置html文件路径 folder_path = r'C:\Users\test\Desktop\DIDItest' output_file = r'C:\Users\test\Desktop\output.csv' # 提取html文件内所需要数据 def extract_html_info(file_path, csv_writer): with open(file_path, 'r', encoding='utf-8') as file: # 读取HTML源代码 html = file.read() soup = BeautifulSoup(html, 'html.parser') # 提取所有的标签 p_tags = soup.find_all('p') for p_tag in p_tags: # 提取ID、时间、发送号码、接收号码和发送内容 talk_id = soup.find('span', class_='hint-success').text.strip() time = soup.find('body').contents[0].strip() send_number = soup.find_all('span', class_='hint-success')[0].text.strip() receive_number = soup.find_all('span', class_='hint-success')[1].text.strip() content = soup.find('p').contents[0].strip() # 判断是否是音频 if '音频' in message: file_url = p_tag.find('a')['href'] csv_writer.writerow([talk_id, timestamp, send_number, receive_number, file_url]) else: csv_writer.writerow([talk_id, timestamp, send_number, receive_number, message]) # 创建CSV文件并写入数据 with open(output_file, 'w', newline='', encoding='utf-8') as file: csv_writer = csv.writer(file) csv_writer.writerow(['ID', '时间', '发送号码', '接收号码', '内容']) # 遍历文件夹及子文件夹,提取HTML文件信息 for root, dirs, files in os.walk(folder_path): for file in files: if file.endswith('.html'): file_path = os.path.join(root, file) extract_html_info(file_path, csv_writer) print("数据已成功写入CSV文件。")

最新推荐

recommend-type

node-v0.10.9-sunos-x86.tar.gz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

ARL-master-wade.zip

ARL-master-wade.zip
recommend-type

paralleled FLUS_V2.4.zip

paralleled FLUS_V2.4.zip
recommend-type

2121212111111111111111111

212111111111111
recommend-type

wx077企业内部员工管理系统-thinkphp5+vue+uniapp-小程序.zip(可运行源码+sql文件+)

wx077企业内部员工管理系统-thinkphp5+vue+uniapp-小程序.zip 企业内部员工管理系统是一个很好的项目,结合了后端(thinkphp5)、前端(Vue.js)和 uniapp 技术,实现了前后端分离。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

SPDK_NVMF_DISCOVERY_NQN是什么 有什么作用

SPDK_NVMF_DISCOVERY_NQN 是 SPDK (Storage Performance Development Kit) 中用于查询 NVMf (Non-Volatile Memory express over Fabrics) 存储设备名称的协议。NVMf 是一种基于网络的存储协议,可用于连接远程非易失性内存存储器。 SPDK_NVMF_DISCOVERY_NQN 的作用是让存储应用程序能够通过 SPDK 查询 NVMf 存储设备的名称,以便能够访问这些存储设备。通过查询 NVMf 存储设备名称,存储应用程序可以获取必要的信息,例如存储设备的IP地址、端口号、名称等,以便能
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。