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 · 3868 次点击
    这是一个创建于 2184 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码这样的:

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

    请大神指点指点

    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   ·   我们的愿景   ·   实用小工具   ·   3698 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 10:24 · PVG 18:24 · LAX 03:24 · JFK 06:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.