代码这样的:
def insertData(db,usr,passwd,values): #插入数据库。INSERT INTO films VALUES #('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes'); cOnn= psycopg2.connect(database=db, user=usr, password=passwd) print(conn) cur = conn.cursor() try: cur.execute("insert into films values(values)") except: print("Failed!") conn.commit() cur.close() conn.close() def errData(fp):#逐行拆分字段,拼成 string 插入数据库。 print("开始处理存在乱码的数据!%s"%fp) values = [] with open(fp) as fh: for line in fh: print(line.strip('\n')) print(line.strip('\n').split('|')) for f in line.strip('\n').split('|'): print(chardet.detect(f)) try: if(chardet.detect(f)['encoding'] in ['ascii','none','','GBK','Big5','GB18030']): print(f.decode(chardet.detect(f))) print(f.decode(chardet.detect(f)['encoding']).encode('utf-8')) else: print(f.decode('utf-8').encode('utf-8')) except: print(f.encode('utf-8')) return values
想请教一下,insertData 插入数据这块,在 errData 里面怎么把 list 转换成 insert 语句的格式呢? errData 这里,V 友给了不少建议。但是我自己写的比较复杂,因为基本上就是中文编码,最大概率的是 utf-8,少数害群之马是其他的中文编码或者 ascii。但是会爆这么个错,说是 object 不应该是个 str,可是先去掉换行符,一定会变成 string 吧。在 python2.7 就没发现这个错。
Traceback (most recent call last): File "./test.py", line 116, in <module> errData(fp) File "./test.py", line 85, in errData print(chardet.detect(f)) File "/opt/anaconda3/lib/python3.6/site-packages/chardet/__init__.py", line 34, in detect '{0}'.format(type(byte_str))) TypeError: Expected object of type bytes or bytearray, got: <class 'str'>
请大神指点指点
![]() | 1 cszeus 2018-05-04 01:38:48 +08:00 把你的 f 手动转成 bytes ? |
2 Arnie97 2018-05-04 01:48:23 +08:00 via Android 你到底是要用 Python 2.7 还是 Python 3 啊?二者的 str 完全是反义词,你直接复制过去能用就鬼了 |
4 sjmcefc2 OP @Arnie97 查了一下 p3 默认是 utf-8,如果这个编码不是 utf-8 的话,那必然乱码,需要先 encode,然后 decode ? 顺序反一下? |
5 Arnie97 2018-05-04 02:03:53 +08:00 via Android str 是 Python 2 的 unicode,bytes 是以前的 str,至于你说的 Python 3 的源代码文件本身是 UTF-8 跟你研究的主题没有任何关系 |
7 Arnie97 2018-05-04 02:44:56 +08:00 via Android 建议你先搞清楚编码是什么原理,从你来 V 站第一天就在纠结这个问题… |
9 andrewblabla 2018-05-04 22:56:20 +08:00 编码转换的背景知识参考 这里 https://qtguide.ustclug.org/ch03-01.htm |