You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地主机(localhost)无法正常显示Unicode字符U+203E的问题求助

解决Unicode字符显示乱码问题

出现乱码的核心原因有两个:一是读取文件时未指定UTF-8编码,二是HTTP响应未明确告知浏览器用UTF-8解析内容。按以下两步修复即可:

1. 读取文件时指定UTF-8编码

Python的open()函数默认使用系统编码(比如Windows下是GBK),直接读取UTF-8格式的file.txt会导致字符解码异常。修改读取逻辑,明确指定编码:

file_to_open = open(self.path[1:], encoding='utf-8').read()

2. 添加Content-Type响应头

在发送响应状态码后、结束响应头之前,添加Content-Type头,告诉浏览器内容是UTF-8编码的文本:

self.send_header('Content-Type', 'text/plain; charset=utf-8')

修改后的完整代码

from http.server import HTTPServer, BaseHTTPRequestHandler


class Serv(BaseHTTPRequestHandler):

    def do_GET(self):
        if self.path == '/':
            self.path = '/file.txt'
        try:
            # 读取文件时指定UTF-8编码
            file_to_open = open(self.path[1:], encoding='utf-8').read()
            self.send_response(200)
            # 告知浏览器使用UTF-8解析内容
            self.send_header('Content-Type', 'text/plain; charset=utf-8')
        except:
            file_to_open = "File not found"
            self.send_response(404)
            self.send_header('Content-Type', 'text/plain; charset=utf-8')
        self.end_headers()
        self.wfile.write(bytes(file_to_open, 'utf-8'))


httpd = HTTPServer(('localhost', 8080), Serv)
httpd.serve_forever()

完成以上修改后,浏览器就能正确识别并显示Unicode字符‾了。

内容的提问来源于stack exchange,提问作者Zen35X

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:39:22