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 12:29:26 浏览: 105
根据你提供的代码,你想遍历指定文件中的所有 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` 列表将是一个空列表。
希望这可以满足你的需求!如果你还有其他问题,请随时提问。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.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)
![](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://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)