我正在编写一些简单的脚本来将文本与 rot13 相互翻译。所以在适当的类(class)中我有这个:
def post(self):
dict = string.maketrans("ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
code = self.request.get("text")
code = string.translate(code, dict)
它可以很好地获取参数“text”,但在 .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)
我的代码有什么问题吗?
最佳答案
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'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~' 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'
关于python - Google App Engine 和 string.translate 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10783141/