尝试用 python 在 babelfish 上自动翻译

发布于 2024-12-10 03:38:48 字数 6410 浏览 0 评论 0原文

我修改了一个 python babelizer 来帮助我将英语翻译成中文。

## {{{ http://code.activestate.com/recipes/64937/ (r4)
# babelizer.py - API for simple access to babelfish.altavista.com.
#                Requires python 2.0 or better.
#
# See it in use at http://babel.MrFeinberg.com/

"""API for simple access to babelfish.altavista.com.

Summary:

    import babelizer

    print ' '.join(babelizer.available_languages)

    print babelizer.translate( 'How much is that doggie in the window?',
                               'English', 'French' )

    def babel_callback(phrase):
        print phrase
        sys.stdout.flush()

    babelizer.babelize( 'I love a reigning knight.',
                        'English', 'German',
                        callback = babel_callback )

available_languages
    A list of languages available for use with babelfish.

translate( phrase, from_lang, to_lang )
    Uses babelfish to translate phrase from from_lang to to_lang.

babelize(phrase, from_lang, through_lang, limit = 12, callback = None)
    Uses babelfish to translate back and forth between from_lang and
    through_lang until either no more changes occur in translation or
    limit iterations have been reached, whichever comes first.  Takes
    an optional callback function which should receive a single
    parameter, being the next translation.  Without the callback
    returns a list of successive translations.

It's only guaranteed to work if 'english' is one of the two languages
given to either of the translation methods.

Both translation methods throw exceptions which are all subclasses of
BabelizerError.  They include

LanguageNotAvailableError
    Thrown on an attempt to use an unknown language.

BabelfishChangedError
    Thrown when babelfish.altavista.com changes some detail of their
    layout, and babelizer can no longer parse the results or submit
    the correct form (a not infrequent occurance).

BabelizerIOError
    Thrown for various networking and IO errors.

Version: $Id: babelizer.py,v 1.4 2001/06/04 21:25:09 Administrator Exp $
Author: Jonathan Feinberg <[email protected]>
"""
import re, string, urllib
import httplib, urllib
import sys

"""
Various patterns I have encountered in looking for the babelfish result.
We try each of them in turn, based on the relative number of times I've
seen each of these patterns.  $1.00 to anyone who can provide a heuristic
for knowing which one to use.   This includes AltaVista employees.
"""
__where = [ re.compile(r'name=\"q\">([^<]*)'),
            re.compile(r'td bgcolor=white>([^<]*)'),
            re.compile(r'<\/strong><br>([^<]*)')
          ]
# <div id="result"><div style="padding:0.6em;">??</div></div>
__where = [ re.compile(r'<div id=\"result\"><div style=\"padding\:0\.6em\;\">(.*)<\/div><\/div>', re.U) ]

__languages = { 'english'   : 'en',
                'french'    : 'fr',
                'spanish'   : 'es',
                'german'    : 'de',
                'italian'   : 'it',
                'portugese' : 'pt',
                'chinese' : 'zh'
              }

"""
  All of the available language names.
"""
available_languages = [ x.title() for x in __languages.keys() ]

"""
  Calling translate() or babelize() can raise a BabelizerError
"""
class BabelizerError(Exception):
    pass

class LanguageNotAvailableError(BabelizerError):
    pass
class BabelfishChangedError(BabelizerError):
    pass
class BabelizerIOError(BabelizerError):
    pass

def saveHTML(txt):
    f = open('page.html', 'wb')
    f.write(txt)
    f.close()

def clean(text):
    return ' '.join(string.replace(text.strip(), "\n", ' ').split())

def translate(phrase, from_lang, to_lang):
    phrase = clean(phrase)
    try:
        from_code = __languages[from_lang.lower()]
        to_code = __languages[to_lang.lower()]
    except KeyError, lang:
        raise LanguageNotAvailableError(lang)
    html = ""
    try:
        params = urllib.urlencode({'ei':'UTF-8', 'doit':'done', 'fr':'bf-res', 'intl':'1' , 'tt':'urltext', 'trtext':phrase, 'lp' : from_code + '_' + to_code , 'btnTrTxt':'Translate'})
        headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
        conn = httplib.HTTPConnection("babelfish.yahoo.com")
        conn.request("POST", "http://babelfish.yahoo.com/translate_txt", params, headers)
        response = conn.getresponse()
        html = response.read()
        saveHTML(html)
        conn.close()
        #response = urllib.urlopen('http://babelfish.yahoo.com/translate_txt', params)
    except IOError, what:
        raise BabelizerIOError("Couldn't talk to server: %s" % what)
    #print html
    for regex in __where:
        match = regex.search(html)
        if match: 
            break
    if not match: 
        raise BabelfishChangedError("Can't recognize translated string.")
    return match.group(1)
    #return clean(match.group(1))

def babelize(phrase, from_language, through_language, limit = 12, callback = None):
    phrase = clean(phrase)
    seen = { phrase: 1 }
    if callback:
        callback(phrase)
    else:
        results = [ phrase ]
    flip = { from_language: through_language, through_language: from_language }
    next = from_language
    for i in range(limit):
        phrase = translate(phrase, next, flip[next])
        if seen.has_key(phrase): break
        seen[phrase] = 1
        if callback:
            callback(phrase)
        else:
            results.append(phrase)
        next = flip[next]
    if not callback: return results

if __name__ == '__main__':
    import sys
    def printer(x):
        print x
        sys.stdout.flush();


    babelize("I won't take that sort of treatment from you, or from your doggie!",
             'english', 'french', callback = printer)
## end of http://code.activestate.com/recipes/64937/ }}}

测试代码是

import babelizer
print ' '.join(babelizer.available_languages)
result = babelizer.translate( 'How much is that dog in the window?', 'English', 'chinese' )
f = open('result.txt', 'wb')
f.write(result)
f.close()
print result

The result is to be displayed inside a div block 。我修改了脚本以保存 html 响应。我发现所有 utf8 字符都变成了 nul 。我在处理 utf8 响应时需要特别小心吗?

I have modified a python babelizer to help me to translate english to chinese.

## {{{ http://code.activestate.com/recipes/64937/ (r4)
# babelizer.py - API for simple access to babelfish.altavista.com.
#                Requires python 2.0 or better.
#
# See it in use at http://babel.MrFeinberg.com/

"""API for simple access to babelfish.altavista.com.

Summary:

    import babelizer

    print ' '.join(babelizer.available_languages)

    print babelizer.translate( 'How much is that doggie in the window?',
                               'English', 'French' )

    def babel_callback(phrase):
        print phrase
        sys.stdout.flush()

    babelizer.babelize( 'I love a reigning knight.',
                        'English', 'German',
                        callback = babel_callback )

available_languages
    A list of languages available for use with babelfish.

translate( phrase, from_lang, to_lang )
    Uses babelfish to translate phrase from from_lang to to_lang.

babelize(phrase, from_lang, through_lang, limit = 12, callback = None)
    Uses babelfish to translate back and forth between from_lang and
    through_lang until either no more changes occur in translation or
    limit iterations have been reached, whichever comes first.  Takes
    an optional callback function which should receive a single
    parameter, being the next translation.  Without the callback
    returns a list of successive translations.

It's only guaranteed to work if 'english' is one of the two languages
given to either of the translation methods.

Both translation methods throw exceptions which are all subclasses of
BabelizerError.  They include

LanguageNotAvailableError
    Thrown on an attempt to use an unknown language.

BabelfishChangedError
    Thrown when babelfish.altavista.com changes some detail of their
    layout, and babelizer can no longer parse the results or submit
    the correct form (a not infrequent occurance).

BabelizerIOError
    Thrown for various networking and IO errors.

Version: $Id: babelizer.py,v 1.4 2001/06/04 21:25:09 Administrator Exp $
Author: Jonathan Feinberg <[email protected]>
"""
import re, string, urllib
import httplib, urllib
import sys

"""
Various patterns I have encountered in looking for the babelfish result.
We try each of them in turn, based on the relative number of times I've
seen each of these patterns.  $1.00 to anyone who can provide a heuristic
for knowing which one to use.   This includes AltaVista employees.
"""
__where = [ re.compile(r'name=\"q\">([^<]*)'),
            re.compile(r'td bgcolor=white>([^<]*)'),
            re.compile(r'<\/strong><br>([^<]*)')
          ]
# <div id="result"><div style="padding:0.6em;">??</div></div>
__where = [ re.compile(r'<div id=\"result\"><div style=\"padding\:0\.6em\;\">(.*)<\/div><\/div>', re.U) ]

__languages = { 'english'   : 'en',
                'french'    : 'fr',
                'spanish'   : 'es',
                'german'    : 'de',
                'italian'   : 'it',
                'portugese' : 'pt',
                'chinese' : 'zh'
              }

"""
  All of the available language names.
"""
available_languages = [ x.title() for x in __languages.keys() ]

"""
  Calling translate() or babelize() can raise a BabelizerError
"""
class BabelizerError(Exception):
    pass

class LanguageNotAvailableError(BabelizerError):
    pass
class BabelfishChangedError(BabelizerError):
    pass
class BabelizerIOError(BabelizerError):
    pass

def saveHTML(txt):
    f = open('page.html', 'wb')
    f.write(txt)
    f.close()

def clean(text):
    return ' '.join(string.replace(text.strip(), "\n", ' ').split())

def translate(phrase, from_lang, to_lang):
    phrase = clean(phrase)
    try:
        from_code = __languages[from_lang.lower()]
        to_code = __languages[to_lang.lower()]
    except KeyError, lang:
        raise LanguageNotAvailableError(lang)
    html = ""
    try:
        params = urllib.urlencode({'ei':'UTF-8', 'doit':'done', 'fr':'bf-res', 'intl':'1' , 'tt':'urltext', 'trtext':phrase, 'lp' : from_code + '_' + to_code , 'btnTrTxt':'Translate'})
        headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
        conn = httplib.HTTPConnection("babelfish.yahoo.com")
        conn.request("POST", "http://babelfish.yahoo.com/translate_txt", params, headers)
        response = conn.getresponse()
        html = response.read()
        saveHTML(html)
        conn.close()
        #response = urllib.urlopen('http://babelfish.yahoo.com/translate_txt', params)
    except IOError, what:
        raise BabelizerIOError("Couldn't talk to server: %s" % what)
    #print html
    for regex in __where:
        match = regex.search(html)
        if match: 
            break
    if not match: 
        raise BabelfishChangedError("Can't recognize translated string.")
    return match.group(1)
    #return clean(match.group(1))

def babelize(phrase, from_language, through_language, limit = 12, callback = None):
    phrase = clean(phrase)
    seen = { phrase: 1 }
    if callback:
        callback(phrase)
    else:
        results = [ phrase ]
    flip = { from_language: through_language, through_language: from_language }
    next = from_language
    for i in range(limit):
        phrase = translate(phrase, next, flip[next])
        if seen.has_key(phrase): break
        seen[phrase] = 1
        if callback:
            callback(phrase)
        else:
            results.append(phrase)
        next = flip[next]
    if not callback: return results

if __name__ == '__main__':
    import sys
    def printer(x):
        print x
        sys.stdout.flush();


    babelize("I won't take that sort of treatment from you, or from your doggie!",
             'english', 'french', callback = printer)
## end of http://code.activestate.com/recipes/64937/ }}}

and the test code is

import babelizer
print ' '.join(babelizer.available_languages)
result = babelizer.translate( 'How much is that dog in the window?', 'English', 'chinese' )
f = open('result.txt', 'wb')
f.write(result)
f.close()
print result

The result is to be expected inside a div block . I modded the script to save the html response . What I found is that all utf8 characters are turned to nul . Do I need take special care in treating the utf8 response ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

π浅易 2024-12-17 03:38:48

我认为你需要

import codecs
codecs.open

在你的: 方法中使用: 而不是普通的 open

saveHTML

来处理 utf-8 文档。有关完整的信息,请参阅 Python Unicode Howto解释。

I think you need to use:

import codecs
codecs.open

instead of plain open, in your:

saveHTML

method, to handle utf-8 docs. See the Python Unicode Howto for a complete explanation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文