python - 打开文件并从 html Python 中提取文本的函数
问题描述
我对 Python 很陌生,我正在尝试编写一个程序来提取 html 标签(不带标签)中的文本并将其写入不同的文本文件以供将来分析。我也提到了这个和这个。我来了能够得到下面的代码。但是我怎么能把它写成一个单独的函数呢?就像是
"def read_list('file1.txt')
然后做同样的刮?我问的原因是此代码的输出(op1.txt)
将用于词干提取,然后用于其他计算。此代码的输出也没有按预期逐行编写。非常感谢您的任何意见!
f = open('file1.txt', 'r')
for line in f:
url = line
html = urlopen(url)
bs = BeautifulSoup(html, "html.parser")
content = bs.find_all(['title','h1', 'h2','h3','h4','h5','h6','p'])
with open('op1.txt', 'w', encoding='utf-8') as file:
file.write(f'{content}\n\n')
file.close()
解决方案
像这样试试
from urllib.request import urlopen
from bs4 import BeautifulSoup
def read_list(fl):
with open(fl, 'r') as f:
for line in f:
html = urlopen(line.strip()).read().decode("utf8")
bs = BeautifulSoup(html, "html.parser")
content = '\n'.join([x.text for x in bs.find_all(['title','p']+[f'h{n}' for n in range(1,7)])])
with open('op1.txt', 'w', encoding='utf-8') as file:
file.write(f'{content}\n\n')
推荐阅读
- powerbi - 在 PowerBI 报告中显示一小时的总分钟利用率
- algorithm - 如何采用在 2D 空间中运行良好的算法并使其适应 3D 环境?
- idris - Prelude 如何允许 Nat 使用数字文字?
- chart.js - 当用户调整页面大小时图表变得混乱
- c - 程序内存中的 utf-8 字符串 (__flash)
- integration-testing - xUnit IClassFixture 构造函数被多次调用
- javascript - 如何在 HTML 中创建无限 JavaScript 循环?
- java - 在 for 循环期间无法附加到我的数组
- javascript - 你如何过滤没有键的javascript嵌套数组
- python - LSTM Keras 整理 X 和 y 输入维度