繁体   English   中英

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

[英]How to open multiple .html files AND remove tags with Python (pyCharm)

我目前正在用 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背景,你打开该文件,并在离开它,文件被关闭。 您不需要它,因为您已经在调用第一个程序的第二个程序中手动关闭了该文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM