提问人:user2105386 提问时间:6/2/2023 最后编辑:user2105386 更新时间:6/8/2023 访问量:174
在 Python 中读取带有“ê : você”字符的葡萄牙语文本文件时出现问题
Issue reading Portuguese text file with "ê : você" character in Python
问:
我有一个使用 PHP 创建的葡萄牙语文本文件,其中包含带有字符“ê”(带有 circumflex 重音的 e)的句子。我正在尝试在 Python 中读取此文件,但我遇到了专门与“ê”字符有关的问题。我已确保 PHP 文件和 Python 脚本都使用 UTF-8 编码。
Python 脚本在终端中工作正常,但是当我从 php exec() 或 shell_exec() 函数调用此 python 文件时,python 无法正确读取文本文件内容并打印此错误:
'ascii' codec can't encode character '\xea' in position 6: ordinal not in range(128)
是什么原因导致了这个问题,我该如何解决?
我已经尝试了以下步骤:
- 使用 UTF-8 编码保存 PHP 文件。
- 在 Python 中打开文件时显式指定 UTF-8 编码。
- 验证 Python 中的默认编码是否设置为 UTF-8。
操作系统: Linux
Python 默认编码:utf-8
文本文件内容:
Se você tem 1 laranja e 1 limão faça esse delicioso bolo!
Python 代码:
filename = "newfile.txt"
with open(filename, "r", encoding="utf-8") as file:
# Read the first line of the text file
file_content = file.readline().strip()
print(file_content)
终端打印:
PHP文件代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>read python</title>
</head>
<body>
<?php
$pythonScript = "read.py";
$command = "python3 " . $pythonScript;
$output = shell_exec($command);
echo $output;
?>
</body>
</html>
我感谢任何关于如何处理这个问题的见解或建议。谢谢!
答:
ASCII 字符串中的首字母是字节顺序标记 (BOM) 字符,有时用作 UTF-8 文件的签名。用于删除它。字符串的其余部分是正确的,因此问题在于显示的编码,而不是 Python。如果您的终端未配置为 UTF-8,它将错误解码结果。在命令提示符下使用 Python 3.11 的 Windows 上,包含该内容的字符串将正确打印:Se você tem 1 laranja e 1 limão faça esse delicioso bolo!.
\ufeff
encoding='utf-8-sig'
@MarkTolonen是对的,终端没有为 UTF-8 配置,我在 php 中使用 exec() 函数之前在终端中设置了本地 utf-8,现在它正在工作。
PHP代码:
$locale='pt_BR.UTF-8';
setlocale(LC_ALL,$locale);
putenv('LC_ALL='.$locale);
评论
print(ascii(file_content))
\ufeff
encoding='utf-8-sig'
Se você tem 1 laranja e 1 limão faça esse delicioso bolo!