You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python提取JSON数据写入SQLite3时type字段取值错误问题求助

问题根源

你代码里的type字段错误取值为实体对象的第一个属性名(比如hashtag实体的text属性),但你需要的实体类型本质是entities对象的键名(即hashtags/urls这类值),直接用外层循环的键即可。

修改方案

核心修改点

  1. 丢弃原有从实体属性取类型的逻辑,直接用entities遍历得到的键作为实体类型,调用capitalize()即可实现首字母大写的格式要求
  2. 修复实体值的取值逻辑,不要取整条推文的full_text,而是取实体对象内对应属性的值
  3. 增加同类型多实体遍历逻辑,避免漏存同类型下的多个实体

修改后可运行代码

import json
import sqlite3

# 自行补充你的数据库连接初始化逻辑
conn = sqlite3.connect('你的数据库名.db')
c = conn.cursor()
# 你自己定义的合法实体类型集合
entities_types = {"hashtags", "symbols", "user_mentions", "urls"}

# 用上下文管理器读取文件避免资源泄漏
with open('tweet.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

for item in data:
    entities = item.get('entities', {})
    tweet_id = item['id']
    # 遍历所有实体类型和对应实体列表
    for entity_type, entity_list in entities.items():
        # 跳过不在合法类型里、或者实体列表为空的项
        if entity_type not in entities_types or not entity_list:
            continue
        # 遍历该类型下所有实体,解决只存第一个实体的问题
        for entity in entity_list:
            # 自动匹配实体值对应的键:hashtags->text,urls->url
            value_key = entity_type[:-1] if entity_type.endswith('s') else entity_type
            type_value = entity.get(value_key, '')
            # 提取起止索引
            start_index, end_index = entity.get('indices', [0, 0])
            # 插入数据,entity_type.capitalize()实现首字母大写
            insert_sql = '''
            INSERT INTO entities (tweet_id, type, value, start_index, end_index)
            VALUES (?,?,?,?,?);
            '''
            c.execute(insert_sql, (tweet_id, entity_type.capitalize(), type_value, start_index, end_index))

conn.commit()
# 验证查询
with conn:
    c.execute("SELECT * FROM entities")
    print(c.fetchall())

效果验证

运行后查询得到的type字段就会输出Hashtags、Urls这类符合你预期的实体类型值,实体内容和起止位置也会对应正确。

内容的提问来源于stack exchange,提问作者user14135159

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:45:01