我还想在excel第二列添加对应的每个html的名称方便我做出匹配该怎么做
时间: 2024-09-19 09:02:40 浏览: 34
要在Excel的第二列添加对应HTML文件的名称,可以在提取HTML内容的同时,记录下每个HTML文件的路径。你可以修改遍历文件夹的部分,将文件名作为新的一列加入到DataFrame中。以下是示例代码:
```python
import os
import pandas as pd
file_dir = "D:\继续采集\APELOA普洛药业\html"
all_texts = [] # 存放所有文件的文本
file_names = [] # 存放文件名
for filename in iglob(os.path.join(file_dir, '*.html')):
abs_path = os.path.abspath(filename)
decoded_path = os.fsdecode(abs_path)
file_name = os.path.basename(decoded_path) # 获取文件名
with open(decoded_path, 'r', encoding='utf-8') as file:
soup = BeautifulSoup(file, 'html.parser')
text_tags = soup.find_all('p')
texts_for_file = [tag.get_text() for tag in text_tags]
# 将文本和文件名分别添加到列表
all_texts.extend(texts_for_file)
file_names.extend([file_name] * len(texts_for_file))
df = pd.DataFrame(list(zip(file_names, all_texts)), columns=['File Name', 'Merged Text'])
df.to_excel('output.xlsx', index=False)
```
这段代码会创建一个新的DataFrame `df`,其中包含两列:'File Name' 和 'Merged Text',这样你就可以清楚地看到每个段落文本对应的HTML文件名称了。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)