【问题标题】:python html parser doesnot return results?python html解析器不返回结果?
【发布时间】: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()

【问题讨论】:

    标签: python-2.7 html-parsing


    【解决方案1】:

    我挣扎了很多,然后尝试了一些更简单的方法,对于上面的代码,我们可以通过以下代码修改 main() 函数,然后这将返回所有 html 文件的 .txt 文件,我们只需要传递文件夹位置。

        def main():
            dir_path = r"/home/maitreyee/Downloads/SchoolCollege.com/rajasthan_data/"
            results_dir = r"/home/maitreyee/Downloads/SchoolCollege.com/rajasthan_data/"
            for file_name in glob.glob(os.path.join(dir_path, "*.html")):
                f = open(file_name)
                text = f.read()
                results_file = os.path.splitext(file_name)[0] + '.txt'  
                with open(results_file, "w") as fp:
                    fp.write(dehtml(text))
                    fp.close()
    

    在给出目录路径的地方,然后将目录路径放入到您的 html 文件的文件夹中。这对我来说真的很有帮助,因为我必须转换数百个 html 文件,而且我需要它们中的所有文本,这在几秒钟内就给了我结果。

    【讨论】:

      猜你喜欢
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多