如何使用Python(pyCharm)打开多个.html文件并删除标记



我目前正在Python中进行一个项目,我必须编写一个程序,从HTML文件中删除所有标记(因此只保留文本(,但我需要为大约1000个HTML文件执行此操作。

这是我用来删除标签的代码:


with open('/inetpub/wwwroot/content/html/eng/0320-0130.htm') as html_file:
source = html_file.read()
html = HTML (html = source)

print(html.text)

&

这是打开多个HTML文件的代码:

import glob
path = '/inetpub/wwwroot/content/html/eng/*.htm'
files=glob.glob(path)
for file in files:
f=open(file, 'r')
print('%s' % f.readlines())
f.close()

我不知道如何组合这些代码,也不知道我需要哪个代码来进行这样的组合。有什么建议吗?

也许您因为第一个程序中使用的with上下文而感到困惑,但将这两个程序组合起来是相当简单的

import glob

def get_html_text(html_file):
source = html_file.read()
html = HTML(html=source)
return html.text

path = '/inetpub/wwwroot/content/html/eng/*.htm'
files = glob.glob(path)
html_texts = []
for file in files:
f = open(file, 'r')
html_texts.append(get_html_text(f))
f.close()
print(len(html_texts))
# print(html_text) # this may lay huge print to your screen if you have many files

with上下文中,它在上面的程序中所要做的就是定义入口和出口操作,即在with上下文下输入这段代码时,打开文件,退出文件时关闭文件。你不需要它,因为你已经在调用第一个程序的第二个程序中手动关闭了文件。

最新更新