2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WindowsにてCP932(Shift-JIS)エンコード以外を開く際の注意点

Posted at

はじめに

 現在、機械学習を学習している初心者です。kaggleにて先人のコードを模写することでその方法を学んでいた時に起きたエラーとその解決方法を備忘としてまとめます。

 概要としては、Windowsの場合はデフォルトでCP932へ変換しようとします。しかし、CP932に変換出来ない場合は、UnicodeEncodeError例外が発生するため、その対処方法をまとめました。

参考url
https://qiita.com/Yuu94/items/9ffdfcb2c26d6b33792e

環境

Windows 10 Home
Python 3.7.4.

問題点と解決方法


embedding_dict={}
with open('xxxxx.txt','r') as f: 
    for line in f:
        values=line.split()
        word = values[0]
        vectors=np.asarray(values[1:],'float32')
        embedding_dict[word]=vectors
f.close()

UnicodeDecodeError: 'cp932' codec can't decode byte 0x93 in position 5456: illegal multibyte sequence

と出ました。
 これは、Windows環境を使用している場合、デフォルトはcp932でコーディングされるとのこと。その場合、変換できないコードが含まれている場合はエラーが出ます。今回具体的なコードは不明ですが、kaggleにて海外の方のコードを模写しているためと思われます。

従って、プログラムにUTF-8でコーディングする様に記述を加えます。


embedding_dict={}
with open('xxxxx.txt','r',encoding="utf-8") as f:
    for line in f:
        values=line.split()
        word = values[0]
        vectors=np.asarray(values[1:],'float32')
        embedding_dict[word]=vectors
f.close()

encoding="utf-8"を加えるだけ、ですがこれで解決しました。

 エラー自体はWindows特有の課題であることやコーディングのされかたについて学ぶことができました。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?