提取talk_id、时间(时间转化为‘0000-00-00’格式)、发送ID、接收ID、信息类型(如果是向设置为私聊,如果是在群设置为群聊)、发送内容(如果是语音或图片设置默认值空值,反之则提取信息内容)、文件名(如果是图片、语音提取<a href=后面的链接地址)

时间: 2024-04-16 07:24:30 浏览: 21
要提取 `talk_id`、时间、发送ID、接ID、信息类型、发送内容和文件,您可以使用正则表达式和 `BeautifulSoup` 来解析 HTML 代码并提取所需的数据。以下是后的代码示例: ```python import os import re from bs4 import BeautifulSoup # 指定文件夹路径 folder_path = "C:/Users/test/Desktop/DIDItest" # 正则表达式模式 talkid_pattern = r'\[talkid:(\d+)\]' time_pattern = r'\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]' sender_pattern = r'\[sender:(.*?)\]' receiver_pattern = r'\[receiver:(.*?)\]' type_pattern = r'\[type:(.*?)\]' # 遍历文件夹中的所有文件 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() # 解析html代码 soup = BeautifulSoup(html_code, "html.parser") # 提取talk_id talk_id = re.findall(talkid_pattern, html_code) # 提取时间并转换格式 time = re.findall(time_pattern, html_code) time = [t.split()[0] for t in time] # 转化为 '0000-00-00' 格式 # 提取发送ID sender = re.findall(sender_pattern, html_code) # 提取接收ID receiver = re.findall(receiver_pattern, html_code) # 提取信息类型 info_type = re.findall(type_pattern, html_code) info_type = ["私聊" if t == "setting" else "群聊" for t in info_type] # 提取发送内容和文件名 content = [] file_name = [] messages = soup.find_all("div", class_="message") for message in messages: if message.find("a"): # 包含链接,文件名为<a href>标签内的内容 file_link = message.find("a").get("href") file_name.append(file_link.split("/")[-1]) content.append("") # 文件类型,内容为空字符串 else: # 文本类型,提取内容 content.append(message.text.strip()) file_name.append("") # 非文件类型,文件名为空字符串 # 打印提取的数据 for i in range(len(talk_id)): print("talk_id:", talk_id[i]) print("时间:", time[i]) print("发送ID:", sender[i]) print("接收ID:", receiver[i]) print("信息类型:", info_type[i]) print("发送内容:", content[i]) print("文件名:", file_name[i]) print() ``` 这段代码使用了多个正则表达式模式来匹配 `[talkid:数字]`、`[时间]`、`[sender:...]`、`[receiver:...]` 和 `[type:...]` 格式的字符串。然后,使用 `BeautifulSoup` 解析 HTML 代码,并使用正则表达式和 `find_all()` 方法找到所需的数据。最后,打印提取的数据。 请确保您已经安装了 `re` 和 `BeautifulSoup` 库,可以使用以下命令来安装: ``` pip install beautifulsoup4 ```

相关推荐

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) # 剔除和() 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+)<.*?>(.*?)<', 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('= 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

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}")

网页内源代码模板如下: <html> <meta http-equiv="Content=-Type" content="text/html; charset=utf-8"> <head> </head> <body>[talkid:138031370]2014年4月20日 03:55:45 , 111222232323 发送 我们已经是好友了,开始聊天吧! () [talkid:138031371]2014年4月20日 04:45:45 , 111222123456 发送 音频 :[<ahref="files/f/f123fsasfsfsjdfrhf_n.m4a"]>音频 () [talkid:138031372]2014年4月20日 04:55:45 , 111222123456 发送 音频 :[<ahref="files/f/f123fsasfsfsjdfrhf_n.jpg"]>图片 () [talkid:138031373]2014年4月20日 05:55:45 , 1112223234221 发送 我们已经是好友了,开始聊天吧! () [talkid:138031374]2014年4月20日 06:55:45 , 1112221359075 发送 我们已经是好友了,开始聊天吧! () </body> </html> 利用python爬虫,打开C:/Users/test/Desktop/DIDItest文件夹下多个文件夹内的html文件源代码,并爬取源代码中的ID、时间、发送号码、接收号码、发送内容,时间转化为0000-00-00格式,如果发送内容为音频则提取音频所在位置,反之则保留发送内容,并将爬取的内容写入csv中

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("---导入完成-----") 创建sql数据库并将数据导入到sql文件中

<body>[talkid:138031370]2014年4月20日 03:55:45 , 111222232323 发送 我们已经是好友了,开始聊天吧! () [talkid:138031371]2014年4月20日 04:45:45 , 111222123456 发送 音频 :[<ahref="files/f/f123fsasfsfsjdfrhf_n.m4a"]>音频 () [talkid:138031372]2014年4月20日 04:55:45 , 111222123456 发送 图片 :[<ahref="files/f/f123fsasfsfsjdfrhf_n.jpg"]>图片 () </body>python爬虫提取talkid、时间、发送号码、接收号码、信息类型(如果发送的是文字就定义类型为文字、如果是图片就定义为图片,如果是音频就定义为音频)、消息内容(如果发送的是文字就直接提取文字、如果是图片或音频就提取音频图片所在链接地址)

网页内源代码模板如下: <html> <meta http-equiv="Content=-Type" content="text/html; charset=utf-8"> <head> </head> <body>[talkid:138031370]2014年4月20日 03:55:45 , 111222232323 发送 我们已经是好友了,开始聊天吧! () [talkid:138031371]2014年4月20日 04:45:45 , 111222123456 发送 音频 :[<ahref="files/f/f123fsasfsfsjdfrhf_n.m4a"]>音频 () [talkid:138031372]2014年4月20日 04:55:45 , 111222123456 发送 图片 :[<ahref="files/f/f123fsasfsfsjdfrhf_n.jpg"]>图片 () </body> </html> 利用python爬虫,打开C:/Users/test/Desktop/DIDItest文件夹下多个文件夹内的html文件源代码,并将源代码转换为字符串,爬取源代码字符串中的ID、时间、发送号码、接收号码、信息类型、发送内容,如果发送内容不为文本,则提取文件所在链接地址,并将爬取的内容写入csv中,talkid提取[]中talkid:后的数字、时间精确至年月日时分秒、发送号码提取第一个 data-hint"">之间的数字,接收号码提取第二个data-hint"">,信息类型就提取 发送与:之间的文字,如果没有:则定义为文字

最新推荐

recommend-type

grpcio-1.47.0-cp310-cp310-linux_armv7l.whl

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

小程序项目源码-美容预约小程序.zip

小程序项目源码-美容预约小程序小程序项目源码-美容预约小程序小程序项目源码-美容预约小程序小程序项目源码-美容预约小程序小程序项目源码-美容预约小程序小程序项目源码-美容预约小程序小程序项目源码-美容预约小程序小程序项目源码-美容预约小程序v
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

【实战演练】MATLAB用遗传算法改进粒子群GA-PSO算法

![MATLAB智能算法合集](https://static.fuxi.netease.com/fuxi-official/web/20221101/83f465753fd49c41536a5640367d4340.jpg) # 2.1 遗传算法的原理和实现 遗传算法(GA)是一种受生物进化过程启发的优化算法。它通过模拟自然选择和遗传机制来搜索最优解。 **2.1.1 遗传算法的编码和解码** 编码是将问题空间中的解表示为二进制字符串或其他数据结构的过程。解码是将编码的解转换为问题空间中的实际解的过程。常见的编码方法包括二进制编码、实数编码和树形编码。 **2.1.2 遗传算法的交叉和
recommend-type

openstack的20种接口有哪些

以下是OpenStack的20种API接口: 1. Identity (Keystone) API 2. Compute (Nova) API 3. Networking (Neutron) API 4. Block Storage (Cinder) API 5. Object Storage (Swift) API 6. Image (Glance) API 7. Telemetry (Ceilometer) API 8. Orchestration (Heat) API 9. Database (Trove) API 10. Bare Metal (Ironic) API 11. DNS
recommend-type

JSBSim Reference Manual

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

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

【实战演练】时间序列预测用于个体家庭功率预测_ARIMA, xgboost, RNN

![【实战演练】时间序列预测用于个体家庭功率预测_ARIMA, xgboost, RNN](https://img-blog.csdnimg.cn/img_convert/5587b4ec6abfc40c76db14fbef6280db.jpeg) # 1. 时间序列预测简介** 时间序列预测是一种预测未来值的技术,其基于历史数据中的时间依赖关系。它广泛应用于各种领域,例如经济、金融、能源和医疗保健。时间序列预测模型旨在捕捉数据中的模式和趋势,并使用这些信息来预测未来的值。 # 2. 时间序列预测方法 时间序列预测方法是利用历史数据来预测未来趋势或值的统计技术。在时间序列预测中,有许多不
recommend-type

怎么在集群安装安装hbase

您好,关于如何在集群上安装HBase,步骤大致如下: 1. 在HBase官网上下载最新版本的HBase,并解压到需要安装的目录下; 2. 配置HBase的环境变量:将HBase目录的bin子目录加入到PATH环境变量中; 3. 修改HBase配置文件:在HBase目录下的conf子目录中找到hbase-site.xml文件,并进行相应的配置,如指定HBase的Zookeeper节点等; 4. 启动HBase:使用HBase的bin目录下的start-hbase.sh脚本启动HBase; 5. 验证HBase是否正常运行:使用HBase自带的shell命令行工具操作HBase。 注意:以上步