Google App Engine,更改ASCII表格上的字符

时间:2012-12-10 22:29:13

标签: google-app-engine unicode ascii unicode-string

我正在尝试执行以下操作:

在HTML TextArea中,将ASCII表中输入文本的每个字符的位置更改为13个位置(在我的代码中为rot13函数)。

这是Rot13功能:

def rot13(s):
    for a in s:
       print chr(ord(a)+13)

它确实以这种方式工作,但它也会打印标题信息并省略最后一个字符。所以当我在框中输入单词“Hello”时,结果是:

U r y y | Status: 200 Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Content-Length: 4 None

那怎么办呢?

另外,当我尝试这样做时:

def rot13(s):
    for a in s:
       chr(ord(a)+13)
    return s

它返回了我在文本中添加的相同文本,没有我认为会有的更改。据我了解,它不会直接修改's'吗?那怎么办呢?

整个代码如下:

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

form = """<html>
<head><title>Rot13</title></head>
<body>
<form method="post">
Please enter your text here:<br>
<textarea name="text"></textarea>
<input type="submit">
</form>
</body>
</html>
"""

def rot13(s):
    for a in s:
       print chr(ord(a)+13)

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

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

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

2 个答案:

答案 0 :(得分:2)

首先,永远不要在WSGI应用程序中使用print

就rot13而言,Python支持以下内容:

out = in.encode('rot13')

答案 1 :(得分:1)

编辑:这是一个在字符串上执行实际ROT13的函数(我道歉 - 我不知道这是一个实际算法 - 我在上一个答案中提供的方法不会执行真ROT13)。但是,如果您正在寻找一种有效的方法来实现它,那么您将很难击败@ NickJohnson的答案:)这将根据表here进行转换,大写映射为大写和小写映射为小写。这将创建大写和小写字母的映射,通过将组件部分分成两半并翻转它们来映射到它们的ROT13等效字母。然后将“正常”和“反向”列表压缩在一起,并根据生成的键/值对创建字典:

In [1]: import string

In [2]: w = 'SecretWord'

In [3]: uc, lc = string.uppercase, string.lowercase

In [4]: c_keys = uc + lc

In [5]: c_val = uc[13:] + uc[:13] + lc[13:] + lc[:13]

In [6]: d = dict((k, v) for k, v in zip(c_keys, c_val))

In [7]: ''.join(d[i] for i in w)
Out[7]: 'FrpergJbeq'

为了让它更容易可视化,这里是键/值字符串的样子:

In [8]: c_keys
Out[8]: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

In [9]: c_val
Out[9]: 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'

您不想使用print,而是使用self.response.out.write(就像在其他地方一样)。这会将结果写入发送给请求者的HTTP响应(请注意,标题也是response的一部分,但除非在使用self.response.out.write时指定,否则不会打印到屏幕上)。在您的情况下,简化版本可能如下所示:

def rot13(s):
    return ''.join(chr(ord(a)+13) for a in s)

它不是打印每个字符,而是使用您定义的函数构造一个字符串。这将返回该字符串,结果将写为response。您还可以添加其他HTML格式等,但这有望让您走上正确的轨道。

另外,关于为什么你的第二个功能不起作用:

def rot13(s):
    for a in s:
       chr(ord(a)+13)
    return s

它返回s未更改的原因是因为虽然您正在执行chr(ord(a)+13)步骤,但您没有对其执行任何操作。你的函数肯定是在正确的轨道上,所以一种方法让它返回相同的输出到上面例子中的一个是创建一个空列表,将存储每个修改过的字符,然后join列表在最后:

def rot13(s):
    # This is your container
    l = []
    for a in s:
       # Now, instead of just running the function, we add the result to the list
       l.append(chr(ord(a)+13))
    # And finally, we use join to join all the list elements together and return
    # E.g. If your list is ['a', 'b', 'c'], this returns the string 'abc'
    return ''.join(l)