The*_*eBP 5 cgi character-encoding python-3.x
我创建了一个 cgi 脚本(使用 apache 在 localhost 上运行),它将从 textarea 加载文本,然后我将使用它。我对 \xc5\xa1、\xc5\xa5、\xc3\xa9 等字符有问题,它们无法正确显示。我尝试了很多方法。这是我的短代码的一个版本,我只是在其中寻找正确的处理方法。
\n#!C:/Python33/python \n# -*- coding: UTF-8 -*-\n \nimport cgi\nimport cgitb\n\ncgitb.enable()\n\nform = cgi.FieldStorage()\nif form.getvalue('textcontent'):\n text_content = form.getvalue('textcontent')\nelse:\n text_content = ""\n\n\nprint ("Content-type:text/html")\nprint ()\nprint("<!DOCTYPE html>")\nprint ("<html>")\nprint ("<head>")\nprint("<meta charset='UTF-8'></meta>")\nprint ("</head>")\nprint ("<body>")\nprint ("<form>")\nprint ("text_area:<br />")\nprint ("<textarea name='textcontent' rows='5' cols='20'></textarea>")\nprint ("<br />")\nprint ("<input type='submit' value='submit form' />")\nprint ("</form>")\nprint("<p>")\nprint(text_content) \nprint("</p>")\nprint ("</body>")\nprint ("</html>")\nRun Code Online (Sandbox Code Playgroud)\n这种方式使用UTF-8,当我尝试写一些东西时,它看起来像这样(写入textarea并提交):
\n\xc4\x8d\xc3\xadtam -> \xef\xbf\xbd\xef\xbf\xbdtam\nRun Code Online (Sandbox Code Playgroud)\n当我在 html 部分使用 latin-1 作为 python 编码和 utf-8 作为字符集时,它的工作原理如下:
\n\xc4\x8dasa -> \xc4\x8dasa (correctly)\nRun Code Online (Sandbox Code Playgroud)\n但对于带有重音符号的字符(例如 \xc3\xa1no),它会返回错误:
\nUnicodeEncodeError: 'charmap' codec can't encode character '\\\\ufffd' in position 0: character maps to <undefined>\\r\nRun Code Online (Sandbox Code Playgroud)\n用sys.stdout.encoding它写入cp1250编码(在 Windows 下工作)并用sys.getdefaultencoding()它返回utf-8
我也尝试过text_content = (form.getvalue('textcontent')).encode('utf-8'),例如单词\xc4\x8d\xc3\xadslo和结果是b'\\xef\\xbf\\xbd\\xef\\xbf\\xbdslo'
我不知道如何处理这个问题。
\n我需要\xc4\x8d\xc3\xadslo -> \xc4\x8d\xc3\xadslo例如。
更新:现在我有 python 的 UTF-8 作为 html 编码。看起来文本处理(将单词与字典进行比较,..)进展顺利,所以现在唯一的一个问题是输出看起来像 \xef\xbf\xbd\xef\xbf\xbdtam,所以我需要修改它看起来像 \xc4\x8d\xc3\xadtam 而不是 \xef\xbf\xbd\xef\xbf\xbdtam。
\n更新 2:当编码为 UTF-8 时,并且在浏览器中也是 UTF-8 时,它显示 \xef\xbf\xbds,当我将浏览器编码更改为 cp1250 时,它显示正确,但是当我刷新站点或单击“提交”按钮时它写入错误 UnicodeEncodeError: 'charmap' codec can't encode character '\\\\ufffd'
更新3:在linux上尝试过,遇到一些问题后我发现apache服务器使用了错误的编码(ascii),但我还无法解决这个问题。修改 /etc/apache2/envvars为 PATH LANG="sk_SK.UTF-8" 但 gedit 在终端中收到一些警告,表示编辑不好。所以编码还是ascii。
小智 1
这样写你的表格:
<form accept-charset="utf-8">
Run Code Online (Sandbox Code Playgroud)
输入accept-charset = "utf-8"您的表格,它可以解决这个问题
| 归档时间: |
|
| 查看次数: |
1260 次 |
| 最近记录: |