python - Google App Engine 和 string.translate 不起作用

标签 python google-app-engine

我正在编写一些简单的脚本来将文本与 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/

相关文章:

python - 不均匀间隔点之间的直观插值

python - 用 NaN 替换 pandas 系列中的负值和 'blocks"连续零直到第一个正值

python - 为什么在访问 Python 对象属性时使用 getattr() 而不是 __dict__?

ios - 将 google 端点与 sql 结合使用

google-app-engine - 谷歌云平台,Golang 灵活环境 HTTPS 仅适用于自定义域

java - GAE : Incoming emails can not preserve format

java - GAE 上的 HttpClient

python - 检索 pandas 中数据框横截面的索引

python - Pandas 从值中删除第一个字符

java - 关于此异常可能来自何处的任何想法?