主文件(路径1/2/3/.py)
import tornado.web,tornado.ioloop,os.path,tornado.httpserver,random
from tornado.options import define,options
define('port',default=8888,help='运行给定的端口',type=int)class A(tornado.web.RequestHandler):
def get(self):
self.render('index.html')class B(tornado.web.RequestHandler):
def map_by_first_letter(self,text):
mapped=dict()
for line in text.split('\r\n'):
for word in [x for x in line.split(' ') if len(x)>0]:
if word[0] not in mapped:mapped[word[0]]=[]
mapped[word[0]].append(word)
return mapped
def post(self):
source=self.get_argument('source')
change=self.get_argument('change')
source_map=self.map_by_first_letter(source)
change_line=change.split('\r\n')
self.render('changed.html',source_map=source_map,change_line=change_line,choice=random.choice)if __name__=='__main__':
tornado.options.parse_command_line()
app=tornado.web.Application([(r'/index',A),(r'/changed',B)],templates_path=os.path.join(os.path.dirname(__file__),'templates'),static_path=os.path.join(os.path.dirname(__file__),'static'),debug=True)
http_server=tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
index.html(路径:1/2/3/.html 和1/2/3/templates/.html)
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href="{{ static_url('style.css')}}">
<title>操作</title>
</head>
<body>
<h1>替换操作</h1>
<p>在下面输入两个文本,将其中每个单词替换成源文本中首字母相同的某个单词。</p>
<form method='post' action='/changed'>
<p>Source text<br>
<textarea rows=4 cols=55 name='source'></textarea></p>
<p>Text to replacement<br>
<textarea rows=4 cols=55 name='change'></textarea></p>
<input type='submit'>
</form>
</body>
</html>
changed.html(路径:1/2/3/.html 和1/2/3/templates/.html)
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href="{{ static_url('style.css')}}">
<title>操作</title>
</head>
<body>
<h1>替换操作</h1>
<p>在下面输入两个文本,将其中每个单词替换成源文本中首字母相同的某个单词。</p>
<form method='post' action='/changed'>
<p>Source text<br>
<textarea rows=4 cols=55 name='source'></textarea></p>
<p>Text to replacement<br>
<textarea rows=4 cols=55 name='change'></textarea></p>
<input type='submit'>
</form>
</body>
</html>
style.css(路径:1/2/3/static/.css)
body{
font-family :Helvetica,Arial,sans-serif;
width:600px;
margin:0 auto;
}
.replace:hover { color:#00f;}
结果如下: