关于自动提取和替换内容的程序

18 views
Skip to first unread message

Li.Ci

unread,
Nov 5, 2012, 1:24:35 AM11/5/12
to fcctt
hi, 各位,我刚刚写了一个小程序,可以从sla 中直接把文章抽取并保存起来。不足之处在于,没法识别浮动框,比如每篇最后的作者介绍,无法自动与相应的文章链接起来,先只能按照页码保存。

稍作改进,我认为可以实现把翻译好的文章从网站中直接扒下来,然后自动替换相应的部分,并自动替换某些特殊的字符等功能。

事实上,我想还可以更进一步,自动替换里面的格式和固定部分的翻译,我想这样可以大大减轻排版的压力。

程序用python3.2开发,使用了beautiful soup库(需要单独安装),测试文件为第65期英文sla文件。有兴趣的,也希望帮忙测试其他期的sla。

我需要同期的中文sla和英文sla ,以便实现替换功能功能。

from bs4 import BeautifulSoup

def getPagesNum(bss):
    a=bss.find('document')
    return int(a.get('anzpages'))

def getPage(bss,n):
    return bss.findAll('pageobject',ownpage='%s' % n)

def getText(tag):
    page=['',[]]
    titles=tag.find('trail',parent="Article Title")
    if titles!=None:
        title=tag.find('ch')
        if title!=None :
            page[0]=title
    else :
        b=tag.findAll('itext')
        for item in b:
            page[1].append(item.get('ch'))
    return page

def display(page):
    title=page[0]
    if title!='':print('title:'+title)
    text=''
    for item in page[1]:
        text=text+str(item)
    if text!='':print(text)



def main():
    data=''
    with open('issue65.sla', encoding='utf-8') as slaf:
        data=slaf.read()
    bss=BeautifulSoup(data)
    pagenum=getPagesNum(bss)
    texts=getPage(bss,7)
    for item in texts:
        text=getText(item)
        if text!=None:display(text)
    '''
    for i in range(pagenum):
        texts=getPage(bss,i)
        for item in texts:
            text=getText(item)
            if text!=None:display(text)
    '''

if __name__ == '__main__':
    main()





yuanjin

unread,
Nov 5, 2012, 2:38:09 AM11/5/12
to fc...@googlegroups.com

贊'=^_^=

刘臻

unread,
Nov 5, 2012, 6:03:54 AM11/5/12
to fc...@googlegroups.com
牛~~~~
--
          Yours 刘臻
The shortest answer is doing
            My Blog

360.gif

oppih

unread,
Nov 5, 2012, 7:56:25 AM11/5/12
to fc...@googlegroups.com
Cool ,这样可以不用打开 Scribus 了对吧

-- 
oppih.me
Best Regards : )

360.gif

刘臻

unread,
Nov 5, 2012, 7:59:39 AM11/5/12
to fc...@googlegroups.com
应该是的,直接提取的sla文件
360.gif

Kitty Wu

unread,
Nov 5, 2012, 9:19:34 AM11/5/12
to fc...@googlegroups.com
赞一个~~


2012/11/5 刘臻 <liuzh...@gmail.com>



--

Regards~

吴云
~~~~
               use it , or u'll lose it...
                                       ~00~
360.gif

Li.Ci

unread,
Nov 6, 2012, 7:57:10 PM11/6/12
to fcctt

这个是修改后的用于提取sla文件内容的程序,移除了对beautiful soup的依赖,只需要python3.x 即可执行。sla中的内容按页保存在'no-x'形式的文本文件中,跨越多页的文章以保存在以“起始页”命名的文件中。

python2.x 稍作修改,应该也可以执行,未测试.


#coding=utf-8
#-------------------------------------------------------------------------------
# Name:        slafile
# Purpose:
#
# Author:      dysp...@gmail.com
#
# Created:     07/11/2012
# Copyright:   (c) dysp...@gmail.com 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import re

re_PageNum=re.compile('<DOCUMENT ANZPAGES="(.+?)"',re.I)
re_PageObjects='(<PAGEOBJECT OwnPage="%s".*?</PAGEOBJECT>)'
re_Line=re.compile('(<ITEXT.+?/>)',re.I)
re_Text=re.compile('ch="(.+?)"',re.I)
re_Title=re.compile('<ITEXT.+?ch="(.+?)"[.\s\S]+?<trail PARENT="Article Title"/>',re.I)
re_CH=re.compile('ch=".+?"',re.I)

class SlaFile(object):

    data=''

    def __init__(self,f):
        with open(f,encoding='utf-8') as slaf:
            self.data=slaf.read()

    def getPageNums(self):
        n=re.findall(re_PageNum,self.data)
        if n==[]:return -1
        return n[0]

    def getPageObjects(self,n):
        re_s='(<PAGEOBJECT OwnPage="%s"[.\s\S]+?</PAGEOBJECT>)' % n
        re_po=re.compile(re_s,re.I)
        return re.findall(re_po,self.data)

    def getObjectLines(self,po):
        lines=[]
        n=re.findall(re_Line,po)
        if n!=[]:lines=lines+n
        return lines

    def getPageLines(self,n):
        plines=[]
        pos=self.getPageObjects(n)
        for obs in pos:
            lines=self.getObjectLines(obs)
            if lines!=[]:
                plines=plines+lines
        return plines

    def getArticTitle(self,ob):
        a=re.findall(re_Title,ob)
        if a!=[]:
            return a[0]
        return None

    def getLineText(self,line):
        text=re.findall(re_Text,line)
        if text==[]:
            return None
        else:
            return text[0]

    def getPageContent(self,n):
        content=[]
        content.append('No-%s\n' % n)
        pos=self.getPageObjects(n)
        for ob in pos:
            flag=False
            title=self.getArticTitle(ob)
            if title!=None:
                content.append('TITLE:'+title)
                content.append('\n')
                continue
            lines=self.getObjectLines(ob)
            for line in lines:
                text=self.getLineText(line)
                if text!=None:
                    content.append(text)
                    flag=True
            if flag:content.append('\n')
        return ''.join(content)

    def saveArticle(self,n):
        data=self.getPageContent(n)
        filename='No-%d.txt' % n
        with open (filename,'w',encoding='utf-8') as f:
            f.write(data)
            f.flush()


def main():
    #调用的范例

    #生成类对象,需要传递sla文件信息
    sla=SlaFile('issue65.sla')
    #获取总页码数
    nums=int(sla.getPageNums())
    for i in range(nums):
        #保存第x页中的内容,内容保存在当前路径下
        sla.saveArticle(i)



if __name__ == '__main__':
    main()
360.gif

Li.Ci

unread,
Nov 6, 2012, 8:26:06 PM11/6/12
to fcctt
用于自动获取中文译文的程序。现在按顺序保存在“no-xx-cn”形式的文本文件中,如果按提取程序那样,给译文增加页码号,将有助于后面替换功能的实现。
有兴趣请测试,欢迎回馈。


#coding=utf-8
#-------------------------------------------------------------------------------
# Name:        fcttweb

# Purpose:
#
# Author:      dysp...@gmail.com
#
# Created:     07/11/2012
# Copyright:   (c) dysp...@gmail.com
# Licence:     GPL V3
#-------------------------------------------------------------------------------

from urllib import request
from urllib.parse import urljoin
import re

re_url=re.compile('<td class="content"><a href="(.+?)"',re.I)
re_tbody=re.compile('(<tbody class="tree-entries[.\s\S]+?data-url="/FCCTT/FCM_issue[.\s\S]+?</tbody>)',re.I)
re_article=re.compile('(<article class="[.\s\S]+?</article>)',re.I)
re_Doc=re.compile('>(.*?)<',re.I)

class FcttWeb(object):
    url=''
    def __init__(self,n):
        self.url='https://github.com/FCCTT/FCM_issue%s' % n

    def getWebContent(self,u):
        con=request.urlopen(u)
        webdata=con.read().decode('utf-8')
        return webdata

    def getTbody(self,data):
        n=re.findall(re_tbody,data)
        if n==None:return None
        return n[0]

    def getFileUrlList(self,tbody):
        n=re.findall(re_url,tbody)
        if n==[]:return []
        return n

    def getCNText(self,data):
        doc=[]
        articledata=re.findall(re_article,data)
        if articledata!=[] :
            lines=re.findall(re_Doc,articledata[0])
            for line in lines:
                if len(line)<1:continue
                doc.append(line)
        return ''.join(doc)

    def getArticles(self):
        articles=[]
        webdata=self.getWebContent(self.url)
        tbody=self.getTbody(webdata)
        urlList=[]
        if tbody!=None:
            urlList=self.getFileUrlList(tbody)
        for item in urlList:
            texturl=urljoin(self.url,item)
            text=self.getWebContent(texturl)
            doc=self.getCNText(text)
            if doc!=[]:
                print(doc)
                articles.append(doc)
        return articles

    def saveArticles(self):
        n=1
        for item in self.getArticles():
            filename='No-%d-CN.txt' % n
            with open(filename,'w',encoding='utf-8') as f:
                f.write(item)
                f.flush
            n=n+1

def main():
    #获取第53期
    fw=FcttWeb(53)
    #保存文章
    fw.saveArticles()
360.gif

Li.Ci

unread,
Nov 6, 2012, 8:29:53 PM11/6/12
to fcctt
用于自动获取中文译文的程序。现在按顺序保存在“no-xx-cn”形式的文本文件中,如果按提取程序那样,给译文增加页码号,将有助于后面替换功能的实现。
有兴趣请测试,欢迎回馈。


#coding=utf-8
#-------------------------------------------------------------------------------
# Name:        fcttweb
# Purpose:
#
# Author:      dysp...@gmail.com
#
# Created:     07/11/2012
# Copyright:   (c) dysp...@gmail.com
if __name__ == '__main__':
    main()



在 2012年11月7日 上午8:57,Li.Ci <dysp...@gmail.com>写道:
360.gif
Reply all
Reply to author
Forward
0 new messages