Python实例:文本整理

来源:互联网 发布:淘宝隐藏导航条 编辑:程序博客网 时间:2024/05/17 01:00

好多天没写Python了。

今天写了一个简单的脚本。为了让很久以前的一些html转成txt,然后放进手机里面阅读。

内容都比较简单,就是三个部分:转换单个的html,转换整个文件夹的html,把文件夹内的html合并在一起。

初看起来这个代码好像没什么用。其实下载下来的chm文件,其实就是html来的,或者自己下载整本的小说。

不过现在整本小说一般都是有得下载的,只是很多广告在里面。最近没怎么看小说,等下次看的时候再补充一下。其实就是一些替换函数而已。

from bs4 import BeautifulSoup#解析html结构的模块import os.pathimport osPrefixHtml='.html'PrefixTxt = '.txt'class CTxtManager:    '''    classdocs    '''    def __init__(self):        '''        Constructor        '''        def changeHtmlToText(self, fileName, filePath, tarDir):        '''        把html转成文本        '''         file = open(filePath + '/' + fileName,'rb') #打开代理文件         htmlStr=file.read()#读取出来,这里并没有进行转码,所以是二进制的。        file.close()          #替换掉空格和换行符,必须在使用BeautifulSoup之前执行,否则所有的标签都会被去掉。        htmlStr = htmlStr.replace(b" ",b" ")#使用二进制的字符串        htmlStr = htmlStr.replace(b"<br>",b"\n")#使用二进制的字符串        #使用BeautifulSoup获取相关的内容        soup = BeautifulSoup(htmlStr, 'html.parser') # 开始解析        title = soup.find('div',attrs={'id':'title'}).getText()#标题        content = soup.find('div',attrs={'id':'content1'}).getText()#内容         content = title + '\n' + content                #保存txt文件        fileNames = os.path.splitext(fileName)          file = open(tarDir + '\\' + fileNames[0] + '.txt','wb')#保存这些内容        file.write(content.encode())        file.close()    def changeAllHtml(self, fileDir, tarDir = ""):        '''        把目录下所有的html转换成txt        '''        if tarDir == "":            tarDir = fileDir#不设置生成路径,就在当前路径生成                    for parent, dirnames, filenames in os.walk(fileDir):            for filename in filenames:                if filename.endswith(PrefixHtml) :                    currentTargetDir = parent.replace(fileDir, tarDir) #当前的目标目录                    if not os.path.exists(currentTargetDir):#判断目录是否存在                        os.makedirs(currentTargetDir)#创建多级目录                    self.changeHtmlToText(filename, parent, currentTargetDir)#转换并生产单个txt                        def mergeTxt(self, fileDir, tarFile):        msg = ""        for parent, dirnames, filenames in os.walk(fileDir):            for filename in filenames:                if filename.endswith(PrefixTxt) :                    file = open(parent + '\\' + filename,'rb') #打开代理文件                     msg = msg + file.read().decode('utf-8','ignore') + '\n'#读取出来,这里并没有进行转码,所以是二进制的。                    file.close()         file = open(tarFile,'wb')#保存这些内容        file.write(msg.encode())        file.close()                    if __name__ == '__main__':    #打开html文件     txtManager = CTxtManager()    #转换单个文件    #txtManager.changeHtmlToText(r'x.txt',r"e:\test", r"e:\test2")    #转换多个文件    #txtManager.changeAllHtml(r"e:\test")    #合并txt文件    txtManager.mergeTxt(r'e:\test', r'e:\test\s.txt')


0 0
原创粉丝点击