Google App Engine是否与Python translate()兼容?

问题描述:

在下面我使用translate()来消除字符串中的标点符号。我一直在translate有很多问题,因为它不适用于unicode。但是现在我注意到脚本在开发服务器中运行良好,但在生产服务器中引发了错误。Google App Engine是否与Python translate()兼容?

该请求通过Chrome扩展发送到谷歌应用程序引擎。任何建议如何我可以解决这个问题,以便相同的脚本在生产服务器中工作?或者,如果不使用translate(),还有另一种方法可以消除标点符号。

原木生产服务器:

2011-10-11 06:18:10.384 
get_rid_of_unicode: ajax: how to use xmlhttprequest 
E 2011-10-11 06:18:10.384 
expected a character buffer object 
Traceback (most recent call last): 
    File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/_webapp25.py", line 703, in __call__ 
    handler.post(*groups) 
    File "/base/data/home/apps/ting-1/1.353888928453510037/ting.py", line 2073, in post 
    user_tag_list_case = f1.striplist(main().split(" ")) 
    File "/base/data/home/apps/ting-1/1.353888928453510037/ting.py", line 2055, in main 
    title_no_punctuation = get_rid_of_unicode.translate(None, string.punctuation) 
TypeError: expected a character buffer object 

同样的脚本作品没有问题,在开发服务器:

INFO 2011-10-11 13:15:49,154 ting.py:2052] get_rid_of_unicode: how to use xmlhttprequest 
INFO 2011-10-11 13:15:49,154 ting.py:2057] title_no_punctuation: how to use xmlhttprequest 

脚本:

def main(): 

    title_lowercase = title.lower() 
    title_without_possessives = remove_possessive(title_lowercase) 
    title_without_double_quotes = remove_double_quotes(title_without_possessives) 
    get_rid_of_unicode = title_without_double_quotes.encode('utf-8') 
    title_no_punctuation = get_rid_of_unicode.translate(None, string.punctuation) 
    back_to_unicode = unicode(title_no_punctuation, "utf-8") 
    clean_title = remove_stop_words(back_to_unicode, f1.stop_words) 
    return clean_title 

user_tag_list = [] 
user_tag_list_case = f1.striplist(main().split(" ")) 
for tag in user_tag_list_case: 
    user_tag_list.append(tag.lower()) 

谷歌应用程序引擎运行的Python 2.5.2。 str.translate()需要一个256个字符的字符串作为第一个参数;自Python 2.6以来,None一直是允许的值。

+0

@ Wooble:谢谢。我试图用这个http://*.com/questions/1324067/how-do-i-get-str-translate-to-work-with-unicode-strings/1324274#1324274没有'None',但它给'断言isinstance(to_translate,str)'行的AssertionError'。但同样在IDLE中工作正常,所以我认为这是GAE运行2.5.2的另一个问题。任何建议如何消除与当前GAE版本兼容的非字母和非数字?再次感谢。 – Zeynel

+1

您可以使用[maketrans](http://docs.python.org/library/string.html#string.maketrans)创建您需要传递以进行翻译的翻译表。在你的情况下,你需要枚举非字母和非数字,并将它们映射到空格字符(如果我明白你想要做的是正确的)。正则表达式可能更容易。 –

+0

@ Luke Franci:我尝试了'maketrans'作为这个答案http://*.com/questions/1324067/how-do-i-get-str-translate-to-work-with-unicode-strings/1324274# 1324274但在这种情况下,我得到了'AssertionError'和这个http://*.com/questions/1324067/how-do-i-get-str-translate-to-work-with-unicode-strings/1324461# 1324461像'u'»'这样的字符'给出TypeError TypeError:不支持解码Unicode' – Zeynel