C プログラムに Python インタープリターを組み込みました。C プログラムがファイルから char 配列にいくつかのバイトを読み取り、そのバイトが特定のエンコーディング (ISO 8859-1、Windows-1252、または UTF-8 など) でテキストを表していることを (何らかの方法で) 学習したとします。この char 配列の内容を Python 文字列にデコードするにはどうすればよいですか?
Python 文字列は一般に、型である必要がありunicode
ます。たとえば、0x93
Windows-1252 でエンコードされた入力では a は になりu'\u0201c'
ます。
を使用しようとしPyString_Decode
ましたが、文字列に非 ASCII 文字が含まれていると常に失敗します。失敗する例を次に示します。
#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *py_string;
Py_Initialize();
py_string = PyString_Decode(c_string, 1, "windows_1252", "replace");
if (!py_string) {
PyErr_Print();
return 1;
}
return 0;
}
エラー メッセージは です。これは、 の呼び出しで指定したにもかかわらずUnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)
、エンコーディングが使用されていることを示しています。ascii
windows_1252
PyString_Decode
次のコードは、 を使用してデコードされPyString_FromString
ていないバイトの Python 文字列を作成し、そのdecode
メソッドを呼び出すことで問題を回避します。
#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *raw, *decoded;
Py_Initialize();
raw = PyString_FromString(c_string);
printf("Undecoded: ");
PyObject_Print(raw, stdout, 0);
printf("\n");
decoded = PyObject_CallMethod(raw, "decode", "s", "windows_1252");
Py_DECREF(raw);
printf("Decoded: ");
PyObject_Print(decoded, stdout, 0);
printf("\n");
return 0;
}