一段脏乱差的代码,大神们能给指点一下不?写的太乱他拖沓。。还有点晕 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
sjmcefc2
V2EX    Python

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

  •  
  •   sjmcefc2 2018-05-03 23:47:17 +08:00 4344 次点击
    这是一个创建于 2725 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码这样的:

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

    请大神指点指点

    9 条回复    2018-05-04 22:56:20 +08:00
    cszeus
        1
    cszeus  
       2018-05-04 01:38:48 +08:00
    把你的 f 手动转成 bytes ?
    Arnie97
        2
    Arnie97  
       2018-05-04 01:48:23 +08:00 via Android
    你到底是要用 Python 2.7 还是 Python 3 啊?二者的 str 完全是反义词,你直接复制过去能用就鬼了
    sjmcefc2
        3
    sjmcefc2  
    OP
       2018-05-04 01:50:05 +08:00
    @Arnie97 一开始是用 2.7 的,发现没报错。现在要用 3.6 了。
    不知道这个要怎么破,谢谢大侠。
    sjmcefc2
        4
    sjmcefc2  
    OP
       2018-05-04 01:53:20 +08:00
    @Arnie97 查了一下 p3 默认是 utf-8,如果这个编码不是 utf-8 的话,那必然乱码,需要先 encode,然后 decode ?
    顺序反一下?
    Arnie97
        5
    Arnie97  
       2018-05-04 02:03:53 +08:00 via Android
    str 是 Python 2 的 unicode,bytes 是以前的 str,至于你说的 Python 3 的源代码文件本身是 UTF-8 跟你研究的主题没有任何关系
    sjmcefc2
        6
    sjmcefc2  
    OP
       2018-05-04 02:17:35 +08:00
    @Arnie97 有点晕了。这个还有办法破吗? python3
    Arnie97
        7
    Arnie97  
       2018-05-04 02:44:56 +08:00 via Android
    建议你先搞清楚编码是什么原理,从你来 V 站第一天就在纠结这个问题…
    sjmcefc2
        8
    sjmcefc2  
    OP
       2018-05-04 03:08:21 +08:00
    @Arnie97 确实。不过有点太绕了。有不太长但是系统的资料可以参考吗?
    andrewblabla
        9
    andrewblabla  
       2018-05-04 22:56:20 +08:00
    编码转换的背景知识参考 这里 https://qtguide.ustclug.org/ch03-01.htm
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     2733 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 26ms UTC 14:08 PVG 22:08 LAX 07:08 JFK 10:08
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86