【发布时间】:2016-01-18 18:12:33
【问题描述】:
我是 python 新手,我有一个下载的 html 文件的文件夹,我需要从中提取文本数据并将其输出到与文本文件相同的文件夹中,下面的代码适用于单个文件,但是当我试图传递多个文件它不起作用。请提出解决方案,我将非常感激。它甚至没有给我任何错误,所以我可以解决它并找出一些解决方案。
from HTMLParser import HTMLParser
from re import sub
from sys import stderr
from traceback import print_exc
import glob
import os
class _DeHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.__text = []
def handle_data(self, data):
text = data.strip()
if len(text) > 0:
text = sub('[ \t\r\n]+', ' ', text)
self.__text.append(text + ' ')
def handle_starttag(self, tag, attrs):
if tag == 'p':
self.__text.append('\n\n')
elif tag == 'br':
self.__text.append('\n')
def handle_startendtag(self, tag, attrs):
if tag == 'br':
self.__text.append('\n\n')
def text(self):
return ''.join(self.__text).strip()
def dehtml(text):
try:
parser = _DeHTMLParser()
parser.feed(text)
parser.close()
return parser.text()
except:
print_exc(file=stderr)
return text
def main():
dir_path = r"/home/maitreyee/Downloads/SchoolCollege.com/multiple_states/"
results_dir = r"/home/maitreyee/Downloads/SchoolCollege.com/"
for file_name in glob.glob(os.path.join(dir_path, "*.html")):
text = open(file_name, "r")
results_file = os.path.splitext(file_name)[0] + '.txt'
with open(results_file, 'w') as outfile:
i = dehtml(text)
print(i)
outfile.write(i + '\n')
if __name__ == '__main__':
main()
【问题讨论】: