2012-05-28 66 views
2

我正在寫一些簡單的腳本來將文本翻譯成rot13。所以appriopriate類中我有這樣的:Google App Engine和string.translate不起作用

def post(self): 
dict = string.maketrans("ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm") 

code = self.request.get("text") 
code = string.translate(code, dict) 

它得到的參數「文本」不錯,但在.translate它吹了內部服務器錯誤:

 File "<mypath>\main.py", line 46, in post 
    code = string.translate(code, dict) 
    File "C:\Python27\lib\string.py", line 498, in translate 
    return s.translate(table + s[:0]) 
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 128: ordinal not in range(128) 

這有什麼錯我的代碼?

+2

這純粹是一個Python的問題 - 沒有任何使用App Engine。另外,'dict'對於一個變量來說是一個非常糟糕的名字,因爲它也是一個內置類型的名稱。 –

+0

很高興知道,謝謝:) – Straightfw

回答

2
a = "This is a string".encode("rot13") 
b = a.decode("rot13") 
print b 

它的python; D它正是你想要的。

The Unicode version of translate requires a mapping from Unicode ordinals (which you can retrieve for a single character with ord) to Unicode ordinals. If you want to delete characters, you map to None.

I changed your function to build a dict mapping the ordinal of every character to the ordinal of what you want to translate to:

def translate_non_alphanumerics(to_translate, translate_to=u'_'): 
    not_letters_or_digits = u'!"#%\'()*+,-./:;<=>[email protected][\]^_`{|}~' 
    translate_table = dict((ord(char), translate_to) for char in not_letters_or_digits) 
    return to_translate.translate(translate_table) 

>>> translate_non_alphanumerics(u'<foo>!') u'_foo__' 

edit: It turns out that the translation mapping must map from the Unicode ordinal (via ord) to either another Unicode ordinal, a Unicode string, or None (to delete). I have thus changed the default value for translate_to to be a Unicode literal. For example:

>>> translate_non_alphanumerics(u'<foo>!', u'bad') u'badfoobadbad' 
+0

哈哈,謝謝你,這就是爲什麼我喜歡學習Python,很快它就能夠洗碗:D但是,我很好奇爲什麼我的代碼不起作用,看起來很好對我來說。 – Straightfw

+1

@Straightfw使用翻譯功能小心str和unicode字符串:http://stackoverflow.com/a/1324114/624829 – Boud

+0

好的,謝謝:) – Straightfw

相關問題