2011-10-11 106 views
1

在下面我使用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()) 

回答

2

谷歌應用程序引擎運行的Python 2.5.2。 str.translate()需要一個256個字符的字符串作爲第一個參數;自Python 2.6以來,None一直是允許的值。

+0

@ Wooble:謝謝。我試圖用這個http://stackoverflow.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://stackoverflow.com/questions/1324067/how-do-i-get-str-translate-to-work-with-unicode-strings/1324274# 1324274但在這種情況下,我得到了'AssertionError'和這個http://stackoverflow.com/questions/1324067/how-do-i-get-str-translate-to-work-with-unicode-strings/1324461# 1324461像'u'»'這樣的字符'給出TypeError TypeError:不支持解碼Unicode' – Zeynel