python实现txt文本变json题库

import json
import random
import jieba

# 从ti.txt中读取一段话
with open("ti.txt", "r", encoding="utf-8") as file:
    text = file.read()

# 以句号分割成多个句子
sentences = text.split("。")

# 加载jieba分词库
jieba.initialize()


def generate_json(sentences, filename):
    result = []
    idx = 1

    for sentence in sentences:
        if not sentence.strip():  # 增加对空行的检查
            continue
        seg_list = jieba.lcut(sentence)
        # 如果分词后的列表长度不足2,则跳过这个句子
        if len(seg_list) < 2:
            continue

        ci = ""
        # 确保start_index的范围始终有效
        start_index = random.randint(0, max(0, len(seg_list) - 2))
        for i in range(start_index, len(seg_list) - 1):
            word = "".join(seg_list[i:i + 2])
            if 4 <= len(word) <= 6:
                ci = word
                break
        if not ci and seg_list:
            ci = random.choice(seg_list)

        ju = sentence.replace(ci, "") + "---" + ci

        item = {
            "序号": idx,
            "类别": "填空题",
            "新句子": ju,
            "新词": ci
        }
        result.append(item)
        idx += 1

    with open(filename, "w", encoding="utf-8") as file:
        json.dump(result, file, ensure_ascii=False)

    print("JSON 文件已保存成功!")


# 之后的代码保持不变


# 设置输出的 JSON 文件名
filename = 'sdasd.json'

# 调用函数并传入参数
generate_json(sentences, filename)

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值