从另一个类运行 Python 方法时出现异常

发布于 2024-09-28 14:40:20 字数 3631 浏览 3 评论 0原文

这是我的代码。

import urllib2
import urllib
import json
from BeautifulSoup import BeautifulSoup

class parser:
    """
    This class uses the Beautiful Soup library to scrape the information from
    the HTML source code from Google Translate.

    It also offers a way to consume the AJAX result of the translation, however
    encoding on Windows won't work well right now so it's recommended to use
    the scraping method.
    """

    def fromHtml(self, text, languageFrom, languageTo):
        """
        Returns translated text that is scraped from Google Translate's HTML
        source code.
        """
        langCode={
            "arabic":"ar", "bulgarian":"bg", "chinese":"zh-CN",
            "croatian":"hr", "czech":"cs", "danish":"da", "dutch":"nl",
            "english":"en", "finnish":"fi", "french":"fr", "german":"de",
            "greek":"el", "hindi":"hi", "italian":"it", "japanese":"ja",
            "korean":"ko", "norwegian":"no", "polish":"pl", "portugese":"pt",
            "romanian":"ro", "russian":"ru", "spanish":"es", "swedish":"sv" }

        urllib.FancyURLopener.version = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008070400 SUSE/3.0.1-0.1 Firefox/3.0.1"

        try:
            postParameters = urllib.urlencode({"langpair":"%s|%s" %(langCode[languageFrom.lower()],langCode[languageTo.lower()]), "text":text,"ie":"UTF8", "oe":"UTF8"})
        except KeyError, error:
            print "Currently we do not support %s" %(error.args[0])
            return

        page = urllib.urlopen("http://translate.google.com/translate_t", postParameters)
        content = page.read()
        page.close()

        htmlSource = BeautifulSoup(content)
        translation = htmlSource.find('span', title=text )
        return translation.renderContents()


    def fromAjaxService(self, text, languageFrom, languageTo):
        """
        Returns a simple string translating the text from "languageFrom" to
        "LanguageTo" using Google Translate AJAX Service.
        """
        LANG={
            "arabic":"ar", "bulgarian":"bg", "chinese":"zh-CN",
            "croatian":"hr", "czech":"cs", "danish":"da", "dutch":"nl",
            "english":"en", "finnish":"fi", "french":"fr", "german":"de",
            "greek":"el", "hindi":"hi", "italian":"it", "japanese":"ja",
            "korean":"ko", "norwegian":"no", "polish":"pl", "portugese":"pt",
            "romanian":"ro", "russian":"ru", "spanish":"es", "swedish":"sv" }

        base_url='http://ajax.googleapis.com/ajax/services/language/translate?'
        langpair='%s|%s'%(LANG.get(languageFrom.lower(),languageFrom),
                          LANG.get(languageTo.lower(),languageTo))
        params=urllib.urlencode( (('v',1.0),
                           ('q',text.encode('utf-8')),
                           ('langpair',langpair),) )
        url=base_url+params
        content=urllib2.urlopen(url).read()
        try: trans_dict=json.loads(content)
        except AttributeError:
            try: trans_dict=json.load(content)
            except AttributeError: trans_dict=json.read(content)
        return trans_dict['responseData']['translatedText']

现在,在另一个名为 TestGrounds.py 的类中,我想尝试这两种方法,但出现以下错误:

from Parser import parser

print parser.fromHtml("Hello my lady!", "English", "Italian")

Traceback (most 最近一次调用最后): File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\BabylonPython\src\ TestGrounds.py”,第 3 行,在 print parser.fromHtml("Hello my lady!", "English", "Italian") TypeError: 必须使用解析器实例作为第一个参数调用未绑定的方法 fromHtml() (改为使用 str 实例)

Here is my code.

import urllib2
import urllib
import json
from BeautifulSoup import BeautifulSoup

class parser:
    """
    This class uses the Beautiful Soup library to scrape the information from
    the HTML source code from Google Translate.

    It also offers a way to consume the AJAX result of the translation, however
    encoding on Windows won't work well right now so it's recommended to use
    the scraping method.
    """

    def fromHtml(self, text, languageFrom, languageTo):
        """
        Returns translated text that is scraped from Google Translate's HTML
        source code.
        """
        langCode={
            "arabic":"ar", "bulgarian":"bg", "chinese":"zh-CN",
            "croatian":"hr", "czech":"cs", "danish":"da", "dutch":"nl",
            "english":"en", "finnish":"fi", "french":"fr", "german":"de",
            "greek":"el", "hindi":"hi", "italian":"it", "japanese":"ja",
            "korean":"ko", "norwegian":"no", "polish":"pl", "portugese":"pt",
            "romanian":"ro", "russian":"ru", "spanish":"es", "swedish":"sv" }

        urllib.FancyURLopener.version = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008070400 SUSE/3.0.1-0.1 Firefox/3.0.1"

        try:
            postParameters = urllib.urlencode({"langpair":"%s|%s" %(langCode[languageFrom.lower()],langCode[languageTo.lower()]), "text":text,"ie":"UTF8", "oe":"UTF8"})
        except KeyError, error:
            print "Currently we do not support %s" %(error.args[0])
            return

        page = urllib.urlopen("http://translate.google.com/translate_t", postParameters)
        content = page.read()
        page.close()

        htmlSource = BeautifulSoup(content)
        translation = htmlSource.find('span', title=text )
        return translation.renderContents()


    def fromAjaxService(self, text, languageFrom, languageTo):
        """
        Returns a simple string translating the text from "languageFrom" to
        "LanguageTo" using Google Translate AJAX Service.
        """
        LANG={
            "arabic":"ar", "bulgarian":"bg", "chinese":"zh-CN",
            "croatian":"hr", "czech":"cs", "danish":"da", "dutch":"nl",
            "english":"en", "finnish":"fi", "french":"fr", "german":"de",
            "greek":"el", "hindi":"hi", "italian":"it", "japanese":"ja",
            "korean":"ko", "norwegian":"no", "polish":"pl", "portugese":"pt",
            "romanian":"ro", "russian":"ru", "spanish":"es", "swedish":"sv" }

        base_url='http://ajax.googleapis.com/ajax/services/language/translate?'
        langpair='%s|%s'%(LANG.get(languageFrom.lower(),languageFrom),
                          LANG.get(languageTo.lower(),languageTo))
        params=urllib.urlencode( (('v',1.0),
                           ('q',text.encode('utf-8')),
                           ('langpair',langpair),) )
        url=base_url+params
        content=urllib2.urlopen(url).read()
        try: trans_dict=json.loads(content)
        except AttributeError:
            try: trans_dict=json.load(content)
            except AttributeError: trans_dict=json.read(content)
        return trans_dict['responseData']['translatedText']

Now in another class called TestingGrounds.py I want to try out both methods, but I get the following error:

from Parser import parser

print parser.fromHtml("Hello my lady!", "English", "Italian")

Traceback (most recent call last): File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\BabylonPython\src\TestingGrounds.py", line 3, in
print parser.fromHtml("Hello my lady!", "English", "Italian") TypeError: unbound method fromHtml() must be called with parser instance as first argument (got str instance instead)

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

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

发布评论

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

评论(2

泪痕残 2024-10-05 14:40:20

您必须拥有解析器类的实例,而不是调用类本身的方法。

from Parser import parser

print parser().fromHTML("Hello my lady!", "English", "Italian")

或者

from Parser import parser

p = parser()
p.fromHTML(...)

,您可以将 fromHTML 设为静态方法:

class parser(object):   # you should probably use new-style classes
    ...
    @staticmethod
    def fromHTML(...):
        ...

然后您可以使用它,例如:

from Parser import parser

print parser.fromHTML(...)

You have to have an instance of the parser class, not call the method on the class itself.

from Parser import parser

print parser().fromHTML("Hello my lady!", "English", "Italian")

or

from Parser import parser

p = parser()
p.fromHTML(...)

Alternatively, you could make fromHTML a staticmethod:

class parser(object):   # you should probably use new-style classes
    ...
    @staticmethod
    def fromHTML(...):
        ...

which you could then use like:

from Parser import parser

print parser.fromHTML(...)
硪扪都還晓 2024-10-05 14:40:20

如果您想使用 fromHtml() 作为静态方法,如果您实际上不需要访问解析器中的任何数据成员,则非常有用,您需要这样做(为简洁起见)

class parser:
    @staticmethod
    def fromHtml(text, languageFrom, languageTo):
         # etc.

或者,如果您希望它既是静态方法并且能够成为实例方法...

class parser:
    @classmethod
    def fromHtml(self, text, languageFrom, languageTo):
         # etc.

您现在可以将其用作 parser.fromHtml()parser().fromHtml()

查看您的代码,我认为你只需要一个静态方法。

If you want to use fromHtml() as a static method, useful if you don't really need to access any datamembers in parser, you'll need to do this (cut for brevity)

class parser:
    @staticmethod
    def fromHtml(text, languageFrom, languageTo):
         # etc.

Or, if you want it to be both a static method and have the ability to be an instance method...

class parser:
    @classmethod
    def fromHtml(self, text, languageFrom, languageTo):
         # etc.

You can now use it as parser.fromHtml() or parser().fromHtml()

Looking at your code, I should think you'd only need a static method.

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