[英]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.