一段脏乱差的代码,大神们能给指点一下不?写的太乱他拖沓。。还有点晕

2018-05-03 23:47:17 +08:00
 sjmcefc2

代码这样的:

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','GB2312','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'>

请大神指点指点

3885 次点击
所在节点    Python
9 条回复
cszeus
2018-05-04 01:38:48 +08:00
把你的 f 手动转成 bytes ?
Arnie97
2018-05-04 01:48:23 +08:00
你到底是要用 Python 2.7 还是 Python 3 啊?二者的 str 完全是反义词,你直接复制过去能用就鬼了
sjmcefc2
2018-05-04 01:50:05 +08:00
@Arnie97 一开始是用 2.7 的,发现没报错。现在要用 3.6 了。
不知道这个要怎么破,谢谢大侠。
sjmcefc2
2018-05-04 01:53:20 +08:00
@Arnie97 查了一下 p3 默认是 utf-8,如果这个编码不是 utf-8 的话,那必然乱码,需要先 encode,然后 decode ?
顺序反一下?
Arnie97
2018-05-04 02:03:53 +08:00
str 是 Python 2 的 unicode,bytes 是以前的 str,至于你说的 Python 3 的源代码文件本身是 UTF-8 跟你研究的主题没有任何关系
sjmcefc2
2018-05-04 02:17:35 +08:00
@Arnie97 有点晕了。这个还有办法破吗? python3
Arnie97
2018-05-04 02:44:56 +08:00
建议你先搞清楚编码是什么原理,从你来 V 站第一天就在纠结这个问题…
sjmcefc2
2018-05-04 03:08:21 +08:00
@Arnie97 确实。不过有点太绕了。有不太长但是系统的资料可以参考吗?
andrewblabla
2018-05-04 22:56:20 +08:00
编码转换的背景知识参考 这里 https://qtguide.ustclug.org/ch03-01.htm

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/451940

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX