日语中的python函数

时间:2010-03-26 10:15:41

标签: python internationalization

我在Python中编写了一个函数,用于告诉我这两个单词是否相似。

现在我想在同一个函数中传递日文文本。它给出的错误是“不是ascii字符”。我尝试使用utf-8编码,但后来它给出了同样的错误

Non-ASCII character '\xe3' in file

有没有办法做到这一点?我无法为此生成msg文件,因为2关键字不会是常量。

这是代码

def filterKeyword(keyword, adText, filterType):
if (filterType == 'contains'):
    try :
        adtext = str.lower(adText)
        keyword = str.lower(keyword)
        if (adtext.find(keyword)!=-1):
            return '0'
    except:
        return '1'
if (filterType == 'exact'):
    var = cmp(str.lower(adText), str.lower(keyword))
    if(var == 0 ):
        return '0'

return '1'

我使用了以下内容:

filterKeyword(unicode('ポケモン').encode("utf-8"), unicode('黄色のポケモン').encode("utf-8"), 'contains')

filterKeyword('ポケモン'.encode("utf-8"), '黄色のポケモン'.encode("utf-8"), 'contains')

他们两人都给出了错误。

5 个答案:

答案 0 :(得分:3)

这对我有用:

# -*- coding: utf-8 -*-

def filterKeyword(keyword, adText, filterType):
    # same as yours

filterKeyword(u'ポケモン', u'黄色のポケモン', 'contains')

答案 1 :(得分:1)

请不要这样做:

adtext = str.lower(adText)
keyword = str.lower(keyword)

请这样做:

adtext= adText.lower()
keyword = keyword.lower()

请不要这样做:

cmp(str.lower(adText), str.lower(keyword))

请这样做:

return adText.lower() == keyword.lower()

请不要这样做:

try:
    # something
except:
    # handler

请提供具体的例外情况。像Exception这样的通用(超类)很好。有一些非常规的错误,你无法捕获。

try:
    # something
except Exception:
    # handler

此外,捕获异常的确不太可能返回True。

请不要这样做:

return '1' 
return '0'

你不太可能想要归还一个角色。你更有可能想要返回真或假。

return True
return False

如果你做得好的话,你的代码就会起作用。

>>> u'ポケモン'.lower() == u'黄色のポケモン'.lower()
False
>>> u'ポケモン'.lower() in  u'黄色のポケモン'.lower()
True

答案 2 :(得分:0)

不要使用UTF-8。使用unicodes

答案 3 :(得分:0)

把:

# -*- coding: utf-8 -*-

在脚本的前两行之一。这样解释器就会知道代码和字符串中使用了什么编码。

尽可能使用Unicode字符串。如果运气好的话,这个函数可以很好地与Unicode(例如u"something…"而不是"something...")参数一起使用,即使它不是用Unicode编写的。

答案 4 :(得分:0)

我想好好注意一下:

unicode('ポケモン')(传递给unicode()构造函数的非unicode字符串常量)

不是同样的

u'ポケモン'(一个unicode字符串常量)