2017-01-06 11 views
-2

こんにちは、私は次のコードを持っています:python 2.7.12、出力にうまく機能しているpython3を使用して次の問題を回避するにはどうすればよいですか?

from __future__ import print_function 
#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
import json 

import pandas as pd 
import re 
import threading 
import pickle 

import sqlite3 
#from treetagger import TreeTagger 

conn = sqlite3.connect('Telcel.db') 
cursor = conn.cursor() 
cursor.execute('select id_comment from Tweets') 
id_comment = [i for i in cursor] 
cursor.execute('select id_author from Tweets') 
id_author = [i for i in cursor] 
cursor.execute('select comment_message from Tweets') 
comment_message = [i[0].encode('utf-8').decode('latin-1') for i in cursor] 
cursor.execute('select comment_published from Tweets') 
comment_published = [i for i in cursor] 

:しかし

~/data$ python DBtoList.py 
8003 
8003 
8003 
8003 

私は次のようにのpython3を使用して同じコードを実行したときに、私が得ました:

~/data$ python3 DBtoList.py 
Traceback (most recent call last): 
    File "DBtoList.py", line 21, in <module> 
    comment_message = [i[0].encode('utf-8').decode('latin-1') for i in cursor] 
    File "DBtoList.py", line 21, in <listcomp> 
    comment_message = [i[0].encode('utf-8').decode('latin-1') for i in cursor] 
sqlite3.OperationalError: Could not decode to UTF-8 column 'comment_message' with text 'dancing music ������' 

私はこのラインで検索し、私が見つかりました:

"dancing music " 

私はコードのpython 2で働いている理由、PythonのPythonの3.5.2は、この行でこの文字を解読することはできないようです確認していない:

comment_message = [i[0].encode('utf-8').decode('latin-1') for i in cursor] 

ので、私は提案を感謝したいと思いますこの問題を解決するには、サポートに感謝します。

答えて

2

Python sqlite3 APIを使用してPython 3を格納すると、Python 3自体に問題はありません。私はどこにでも私のデフォルトのエンコーディングとしてutf-8を設定しました。

import sqlite3 

conn = sqlite3.connect(':memory:') 
conn.execute('create table Tweets (comment_message text)') 
conn.execute('insert into Tweets values ("dancing music ")') 
[(tweet,) ] = conn.execute('select comment_message from tweets') 

tweet 

出力:

'dancing music ' 

さて、種類を見てみましょう:あなたは最初からPythonのstrで作業する場合

>>> type(tweet) 
str 

だからすべてが正常です。

ここで、あなたがしようとしていること(encode utf-8、decode latin-1)は、特に文字列にemojisのようなものがある場合はほとんど意味がありません。あなたのつぶやきに何が起こるか見て:

>>> tweet.encode('utf-8').decode('latin-1') 
'dancing music ð\x9f\x98\x9c' 

しかし、今のあなたの問題に:あなたは、UTF-8とは別のエンコーディングを使用して、データベース内の文字列(バイト列)に保存されています。表示されているエラーは、sqlite3ライブラリがこれらのバイトシーケンスのデコードを試みていて、バイトが有効なutf-8シーケンスでないために失敗したために発生します。この問題を解決する唯一の方法は次のとおりです。

  1. は、エンコーディングがconn.text_factory = lambda x: str(x, 'latin-1')を設定することで、文字列をデコードすることエンコーディングを使用してデータベース
  2. に文字列をエンコードするために使用されたかを調べます。これはlatin1を使って文字列を格納したことを前提としています。

次に、デフォルトの動作であるutf-8を使用してエンコードされるように、データベースを実行して値を更新することをお勧めします。

this questionも参照してください。

エンコードの仕組みについては、this articleとお読みください。

+0

私は本当にサポートしていただきありがとうございます私はすべての側面を確認します – neo33

関連する問題