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