【问题标题】:Is Google App Engine compatible with Python translate()?Google App Engine 是否与 Python translate() 兼容?
【发布时间】:2011-12-05 08:01:48
【问题描述】:

下面我使用translate() 来消除字符串中的标点符号。我在使用translate 时遇到了很多问题,因为它不适用于 unicode。但是现在我注意到该脚本在开发服务器中运行良好,但在生产服务器中引发了错误。

请求由 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 google-app-engine


    【解决方案1】:

    Google App Engine 运行 Python 2.5.2。 str.translate() 需要 256 个字符的字符串作为第一个参数;自 Python 2.6 起,None 才成为允许值。

    【讨论】:

    • @Wooble:谢谢。我尝试在没有None 的情况下使用这个stackoverflow.com/questions/1324067/…,但它为assert isinstance(to_translate, str) 提供了AssertionError。但是在 IDLE 中同样可以正常工作,所以我认为这是运行 2.5.2 的 GAE 的另一个问题。有什么建议可以消除与当前 GAE 版本兼容的非字母和非数字吗?再次感谢。
    • 您可以使用maketrans创建您需要传递翻译的翻译表。在您的情况下,您需要枚举所有非字母和非数字并将它们映射到空格字符(如果我理解您要正确执行的操作)。正则表达式可能更容易。
    • @Luke Franci:我尝试将maketrans 作为这个答案stackoverflow.com/questions/1324067/…,但在这种情况下,我得到了AssertionError,并且有了这个stackoverflow.com/questions/1324067/…,像u'»' 这样的字符给出了TypeError @ 987654333@
    猜你喜欢
    • 2012-04-23
    • 1970-01-01
    • 2012-02-15
    • 2014-08-05
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    相关资源
    最近更新 更多