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

问题描述 投票:0回答:1

我目前正在使用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()

我不知道如何组合这些代码,或者我需要哪种代码进行这种组合。有什么建议吗?

python html loops pycharm tags
1个回答
0
投票

也许您由于第一个中使用的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上下文中输入这段代码后,您将打开文件并退出它,该文件已关闭。您不需要它,因为您已经在第二个调用第一个程序的程序中手动关闭了该文件。

© www.soinside.com 2019 - 2024. All rights reserved.