拜托,有人可以用下面的代码帮我吗? 当我运行时,日志说:
return method(*args, **kwargs)
File "C:\Users\CG\Documents\udacity\rot13serendipo\main.py", line 51, in post
text = rot13(text)
File "C:\Users\CG\Documents\udacity\rot13serendipo\main.py", line 43, in rot13
return st.translate(tab)
TypeError: character mapping must return integer, None or unicode
INFO 2012-04-28 20:02:26,862 dev_appserver.py:2891] "POST / HTTP/1.1" 500 -
我知道错误必须在rot13()中。但是,当我在IDE中运行此过程时,它正常工作。
这是我的代码:
import webapp2
form= """
<html>
<head>
<title>Unit 2 Rot 13</title>
</head>
<body>
<h2>Enter some text to ROT13:</h2>
<form method="post">
<textarea name="text"
style="height: 100px; width: 400px;"></textarea>
<br>
<input type="submit">
</form>
</body>
</html> """
def rot13(st):
import string
tab1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
tab2 = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM'
tab = string.maketrans(tab1, tab2)
return st.translate(tab)
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write(form)
def post(self):
text = self.request.get("text")
text = rot13(text)
self.response.out.write(text)
app = webapp2.WSGIApplication([('/', MainHandler)],
debug=True)
提前感谢您的帮助!
答案 0 :(得分:37)
这可能是因为文本输入为unicode:
>>> def rot13(st):
... import string
... tab1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
... tab2 = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM'
... tab = string.maketrans(tab1, tab2)
... return st.translate(tab)
...
>>> rot13('test')
'grfg'
>>> rot13(u'test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in rot13
TypeError: character mapping must return integer, None or unicode
>>>
这个问题涵盖了你的需求:
如果您确定unicode字符串不重要,我猜您可以:
return str(st).translate(tab)