已解决UnicodeEncodeError: 'utf-8' コーデックは位置 42-43 の文字をエンコードできません: サロゲートは許可されていません
エラーコード
シソーラスファイルをtxtに書き込むにはpythonである必要があり、書き込みコードは次のとおりです。
# 保存结果
with open(out_path, 'w', encoding='utf8') as f:
f.writelines([word + '\t' + file_name + '\n' for count, py, word, file_name in GTable])
エラー メッセージのスクリーンショット:
词库名: LOL
词库类型: 角色扮演
描述信息: 666
词库示例: 大龙走起不要怂就是干 小龙叫了你们看着办吧 中单撸起 辅助走你 中团啦 中单速度推塔
Traceback (most recent call last):
File "E:/Python/test3.py", line 139, in <module>
f.writelines([word + '\t' + file_name + '\n' for count, py, word, file_name in GTable])
UnicodeEncodeError: 'utf-8' codec can't encode characters in position 42-43: surrogates not allowed
エラー翻訳
エラー メッセージの翻訳:
Unicode エンコーディング エラー: 'utf-8' コーデックは位置 42 ~ 43 の文字をエンコードできません: サロゲートは許可されていません
エラーの理由
エラーの理由:
一部の文字列は utf-8 でデコードできないため、utf-8 形式に変換できない文字 'ignore' を削除してからデコードできます。
解決
この種のエラーが発生した場合は、文字列の後に次のコードを追加します。
.encode('UTF-8', 'ignore').decode('UTF-8')
書き込みコードを次のように変更します。
# 保存结果
with open(out_path, 'w', encoding='utf-8') as f:
try:
f.writelines([word + '\t' + file_name + '\n' for count, py, word, file_name in GTable])
except:
f.writelines([word.encode('UTF-8', 'ignore').decode('UTF-8') + '\t' + file_name.encode('UTF-8', 'ignore').decode('UTF-8') + '\n' for count, py, word, file_name in GTable])
もう一度書くと成功です!