Python 按照某種匹配條件拆分字符串並存儲數據到數據庫 實例

需求:

提供如下的txt文件


測試u047【[email protected]

自主招生3

測試u008【[email protected]

自主招生6


需要將其拆分爲如下結果:

id  qq                          username

1   [email protected]   測試u047

2                                  自主招生3

3   [email protected]   測試u008

4                                  自主招生6


實現比較簡單,按照 【  作爲匹配條件,然後做字符串的截取,最後存儲到數據庫即可,代碼如下:


#處理53數據  測試u008【[email protected]

import pymysql

#Python3環境


def Handle_str(str1):

    pos = str1.find('【')

    if pos > 0:

        QQ = str1[pos+1:-2]

        names = str1[:pos]

        return QQ,names

    else:

        return ''


f = open('phone53')

data = f.readlines()


db = pymysql.connect(host='xxx', user='lizibin', passwd='xxx', db='crm', charset='utf8',connect_timeout=10)

cursor = db.cursor()


try:

    for i in data:

        pos = i.find('【')

        if pos > 0:

            QQ,names = Handle_str(i)

            sql = 'insert into phone53(qq,username) values("%s","%s");' % (QQ,names)

            cursor.execute(sql)

            db.commit()  #如果發現數據表的id自增了,但卻沒有數據就要考慮是否爲該原因


        else:

            sql = 'insert into phone53(username) values("%s");' % (i)

            cursor.execute(sql)

            db.commit()


except Exception as e:

    print(e)


db.close()

f.close()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章