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

需求:mysql

提供以下的txt文件sql


測試u047【123456@qq.com】數據庫

自主招生3ide

測試u008【456789@qq.com】測試

自主招生6spa


須要將其拆分爲以下結果:字符串

id  qq                          usernameit

1   123456@qq.com   測試u047io

2                                  自主招生3class

3   456789@qq.com   測試u008

4                                  自主招生6


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


#處理53數據  測試u008【456789@qq.com】

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()

相關文章
相關標籤/搜索