在文件中读取中文字符并将其发送到浏览器

Dam*_*n T 1 python unicode http cjk

我正在尝试制作一个程序:

  • 从文件中读取中文字符列表,从中创建字典(将符号与其含义相关联).
  • 选择一个随机字符,并BaseHTTPServer在获得GET请求时使用该模块将其发送到浏览器.

一旦我设法正确地阅读和存储标志(我尝试将它们写入另一个文件以检查我是否正确并且它有效)我无法弄清楚如何将它们发送到我的浏览器.

我连接到127.0.0.1:4321并且我管理的最好的是获得一个(据称)url编码的中文字符及其翻译.

码:

# -*- coding: utf-8 -*-
import codecs
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading
import random
import urllib

source = codecs.open('./signs_db.txt', 'rb', encoding='utf-16')

# Checking utf-16 works fine with chinese characters and stuff :
#out = codecs.open('./test.txt', 'wb', encoding='utf-16')
#for line in source:
#   out.write(line)

db = {}
next(source)
for line in source:
    if not line.isspace():
            tmp = line.split('\t')
            db[tmp[0]] = tmp[1].strip()

class Handler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        message =  threading.currentThread().getName()
        rKey = random.choice(db.keys())
        self.wfile.write(urllib.quote(rKey.encode("utf-8")) + ' : ' + db[rKey])
        self.wfile.write('\n')
        return

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

if __name__ == '__main__':
    server = ThreadedHTTPServer(('localhost', 4321), Handler)
    print 'Starting server, use <Ctrl-C> to stop'
    server.serve_forever()
Run Code Online (Sandbox Code Playgroud)

如果我没有urlencode中文字符,我从python得到一个错误:

self.wfile.write(rKey + ' : ' + db[rKey])
Run Code Online (Sandbox Code Playgroud)

这给了我这个:

UnicodeEncodeError:'ascii'编解码器无法对位置0中的字符u'\ u4e09'进行编码:序数不在范围内(128)

我也尝试用'utf-16'进行编码/解码,但我仍然得到那种错误信息.

这是我的测试文件:

Sign    Translation

?   One
?   Two
?   Three
?   Four
?   Five
?   Six
?   Seven
?   Eight
?   Nine
?   Ten
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:"如何从我的脚本中获取汉字,以便在我的浏览器中正确显示"?

Mar*_*nen 5

通过编写元标记来声明页面的编码,并确保以UTF-8编码整个Unicode字符串:

self.wfile.write(u'''\
    <html>
    <headers>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    </headers>
    <body>
    {} : {}
    </body>
    </html>'''.format(rKey,db[rKey]).encode('utf8'))
Run Code Online (Sandbox Code Playgroud)

和/或声明HTTP内容类型:

self.send_response(200)
self.send_header('Content-Type','text/html; charset=utf-8')
self.end_headers()
Run Code Online (Sandbox Code Playgroud)