首页 > 数据库技术 > 详细

python处理json数据插入数据库——英语单词词库

时间:2021-04-04 22:39:39      阅读:28      评论:0      收藏:0      [点我收藏+]

首先从github上获取别人扒好的词库json数据

https://github.com/kajweb/dict

 

数据格式大致如下

技术分享图片

 

 

接着就可以直接使用python处理数据,并插入数据库了

import sys
from jsonpath import jsonpath
import json
import demjson
import pymysql

#打开文件名为json的文件夹下的json文件
filename = "json\\cet4_2.json"
file = open(filename, ‘r‘, encoding=‘utf-8‘)

#链接数据库
def dbconnect():
    try:
        db = pymysql.connect(
            host=‘localhost‘,
            user=‘root‘,
            passwd=‘123456‘,
            db=‘vocab‘
        )
    except Exception as e:
        sys.exit("Can‘t connect to database")
    return db

#插入数据
def insertDb(word, trans, pos):
    try:
        db = dbconnect()
        cursor = db.cursor()
        cursor.execute(" INSERT INTO toefl(word, trans, pos) VALUES(%s, %s, %s)", (word, trans, pos))
        db.commit()
        cursor.close()
    except Exception as e:
        print(str(e))

#逐行读取json数据
cnt = 0
for line in file.readlines():
    words = line.strip()
    word_json = json.loads(words)
    word = ‘‘.join(jsonpath(word_json, "$..headWord"))
    trans = ‘‘.join(jsonpath(word_json, "$..tranCn"))
    res = demjson.decode(words)
    pos = ((((res.get(‘content‘)).get(‘word‘)).get(‘content‘)).get(‘trans‘))[0].get(‘pos‘)
    # print(word, trans, res, pos)
    insertDb(word, trans, pos)

file.close()

 

插入成功后

技术分享图片

 

 

 

 

 

参考资料:

https://github.com/kajweb/dict

https://www.jb51.net/article/177500.htm

python处理json数据插入数据库——英语单词词库

原文:https://www.cnblogs.com/leftstan/p/14616904.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!