2017-08-14 70 views
0

我很難找出我的代碼有什麼問題,我正在嘗試使用python和谷歌應用程序引擎做一個rot13程序。我一直想弄清楚是什麼問題,但我不能,我的代碼工作正常,直到從文本框中獲取值,但是當我將它傳遞給rot13函數時,它會給我一個500錯誤,提前致謝谷歌應用程序引擎蟒蛇rot13

import webapp2 
import cgi 
form = """<form method="post"> 
    <textarea name="text" style="height: 100px; width: 400px;"></textarea> 
    <br> 
    <br> 
    <input type="submit"/> 
    </form>""" 

def escape_html(s): 
    return cgi.escape(s, quote=True) 

def rot13(s): 
    regular = "abcdefghijklmnopqrstuvwxyz" 
    ciper13 = "nopqrstuvwxyzabcdefghijklm" 
    s = s.translate(s.maketrans(regular, ciper13)) 
    return s 

class MainHandler(webapp2.RequestHandler): 
    def write_form(self): 
     self.response.write(form) 

    def get(self): 
     #self.response.headers['Content-Type'] = 'text/plain' 
     self.write_form() 

    def post(self): 
     text = self.request.get('text') 
     text = escape_html(text) 
     text = rot13(text) 
     self.response.write(text) 

app = webapp2.WSGIApplication([('/', MainHandler)], debug=True) 

回答

1

的問題是在這條線:

>>> s = s.translate(s.maketrans(regular, ciper13)) 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'str' object has no attribute 'maketrans' 

maketransstring模塊的屬性,而不是個別字符串實例。

您需要導入string模塊(import string)和你的代碼更改爲:

>>> s = s.translate(string.maketrans(regular, ciper13)) 

另一種方法是使用內置的腐-13編碼:

>>> s = u'foo' 
>>> s.encode('rot-13') 
'sbb' 
相關問題