2013-01-05 35 views
1

我試圖做一個程序:讀中國字在一個文件中,並將它們發送到瀏覽器

  • 從文件讀中國文字的列表,使得從他們的字典(關聯的標誌與其含義)。
  • 選取一個隨機字符,並將其發送到使用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() 

如果我不進行urlencode中國的人物,我得到一個錯誤蟒蛇:

self.wfile.write(rKey + ' : ' + db[rKey]) 

,給了我這樣的:

UnicodeEncodeError: 'ascii'編解碼器不能在位置0編碼字符u'\ u4e09':序號不在範圍內(128)

我也試着編/用「UTF-16」解碼,我仍然得到這樣的錯誤信息。

這裏是我的測試文件:

Sign Translation 

一 One 
二 Two 
三 Three 
四 Four 
五 Five 
六 Six 
七 Seven 
八 Eight 
九 Nine 
十 Ten 

所以,我的問題是:「我怎樣才能拿到中國漢字是從我的腳本來正確地在我的瀏覽器中顯示」?

回答

5

寫一個meta標籤聲明你的網頁的編碼,並確保整個Unicode字符串編碼爲UTF-8:

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')) 

和/或聲明的HTTP內容類型:

self.send_response(200) 
self.send_header('Content-Type','text/html; charset=utf-8') 
self.end_headers() 
+0

它工作得很好,非常感謝! –

相關問題