【问题标题】:Processing chm files处理 chm 文件
【发布时间】:2011-12-27 14:21:28
【问题描述】:

是否有一个 Python 库可用于处理具有与 HTML 解析器或 BeautifulSoup 相似功能的 chm extension 文件?

【问题讨论】:

    标签: python parsing html-parsing beautifulsoup chm


    【解决方案1】:

    【讨论】:

    【解决方案2】:

    我一直在努力使用 PyCHM 创建从 .chm 文件中提取封面图像的简单缩略图。以下是所有将来发现此问题的人的代码:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import chm.chm as chm
    from bs4 import BeautifulSoup
    from PIL import Image
    import urlparse
    try:
        from cStringIO import StringIO
    except:
        from StringIO import StringIO
    
    class CHMFile:
        def __init__(self, file_name):
            self.chmfile = chm.CHMFile()
            self.chmfile.LoadCHM(file_name)
    
        def create_thumb(self, out_file):       
            image = None
            area = 0 # cover will propably be the biggest image from home page
    
            iui = self.chmfile.ResolveObject(self.chmfile.home) 
            home = self.chmfile.RetrieveObject(iui[1])[1] # get home page (as html)
            tree = BeautifulSoup(home)
            for img in tree.find_all('img'):
                src_attr =  urlparse.urljoin(self.chmfile.home, img.get('src'))
                chm_image = self.chmfile.ResolveObject(src_attr)
                png_data = self.chmfile.RetrieveObject(chm_image[1])[1] # get image (as raw data)
    
                png_img = Image.open(StringIO(png_data))
                new_width, new_height = png_img.size
                new_area = new_width * new_height 
                if(new_area > area and new_width > 50 and new_height > 50): # to ensure image is at least 50x50
                    area = new_area
                    image = png_img
            if image:
                image.save(out_file, format="PNG")
    
    
    if __name__ == '__main__':
        import sys
        if len(sys.argv) != 3:
            print 'Create thumbnail image from an chm file'
            print 'Usage: %s INFILE OUTFILE' % sys.argv[0]
        else:
            chm = CHMFile(sys.argv[1])
            chm.create_thumb(sys.argv[2])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-22
      • 2012-06-20
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 2015-02-27
      相关资源
      最近更新 更多