Word转json转txt,word拆分处理

 前言

因为笔者的word文档是pdf转word得到的,所以word的标题没有级别,手动分级又过于麻烦,笔者想到的方法是 根据字数和换行符来判断标题,我采用15个字作为标题的限制,超过15个字就作为内容存储,这样我的json文件就有了两层结构,一个“title”,一个“content”。这个方法粗糙简单,但还算实用。中间出了一个问题是分割文段采用的是根据'\n'分割,所以判断的时候就不需要将结尾是‘\n’作为一个判断条件了。

这样得到的json文件质量不算完美,但是大部分还是有title,有content,本来想的是把一些字数少的比较零散的content合并,但是考虑到合并之后的txt,大概率也是当垃圾扔掉,所以干脆就直接把content为空的json删除,如果笔者愿意还可以把字数少的json一并删除,不过这样的情况不多,因为我们是按照字数判断title,所以短小的字段都被判定成title,这样的好处是大部分垃圾文段的content都为空,可以直接删除。

 一.Word转json

#注意docx和python-docx两个库冲突,要是同时安装了这两个库会报错。
from docx import Document
import json

# 定义一个函数,用于从Word文档中提取目录内容
def extract_table_of_contents(doc):
    toc = doc.paragraphs  # 获取文档的段落
    toc_entries = []  # 用于存储目录条目
    current_entry = None  # 当前目录条目

    # 遍历文档中的段落
    for entry in toc:
        entry_text = entry.text.strip()  # 去除段落两侧的空白字符
        if not entry_text:
            continue  # 跳过空白段落

        # 将entry_text按换行符分割为多行
        lines = entry_text.split('\n')

        # 根据换行符数量和文本长度确定目录级别
        for line in lines:
            clean_line = line.strip()
            if  len(clean_line) < 15:
                current_entry = {"title": entry_text, "content": []}
                toc_entries.append(current_entry)
            elif len(clean_line) > 15 :
                if current_entry is not None:
                    current_entry["content"].append(entry_text)
                else:
                    toc_entries.append({"title":entry_text , "content":[] })

    return toc_entries

# 定义一个函数,将提取的目录内容转换为JSON结构
def generate_json_from_toc(toc_entries):
    return {"table_of_contents": toc_entries}

# 加载Word文档
doc = Document("C:\\Users\\Lenovo\\Desktop\\安全Ⅰ与安全Ⅱ  安全的过去和未来(1).pdf-2023-10-11-10-58-24-226.docx")  # 替换为您的文档文件名

# 提取目录
toc_entries = extract_table_of_contents(doc)

# 生成JSON结构
toc_json = generate_json_from_toc(toc_entries)

# 将JSON输出到文件
with open("output.json", "w", encoding="utf-8") as json_file:
    json.dump(toc_json, json_file, ensure_ascii=False, indent=2)




 二.Json转txt

import json
import os

# 读取JSON数据
with open('output.json', 'r', encoding='utf-8') as json_file:
    data = json.load(json_file)

# 如果输出目录不存在,创建一个
output_dir = 'output'
os.makedirs(output_dir, exist_ok=True)

# 遍历目录内容
for item in data['table_of_contents']:
    if item['content']:
        # 提取标题和内容
        title = item['title'].replace('\n', '_').replace('/', '_').replace(':', '_').replace('*', '_').replace('?',
                                                                                                               '_').replace(
            '"', '_').replace('<', '_').replace('>', '_').replace('|', '_')
        content = ''.join(item['content'])

        # 以标题作为文件名,创建文本文件
        filename = os.path.join(output_dir, f"{title}.txt")
        with open(filename, 'w', encoding='utf-8') as txt_file:
            txt_file.write(content)

def remove_spaces_and_garbage(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()

            # 删除空格
            content_without_spaces = content.replace(' ', '')

        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(content_without_spaces)

    except Exception as e:
        print(f"An error occurred while processing {file_path}: {e}")


# 获取output目录中的所有txt文件
output_dir = 'output'
for filename in os.listdir(output_dir):
    if filename.endswith('.txt'):
        file_path = os.path.join(output_dir, filename)
        remove_spaces_and_garbage(file_path)

print("空格和乱码已从所有txt文件中删除。")

三.附赠小代码,查看json文件结构

import json

def explore_json_structure(data, parent_key=''):
    if isinstance(data, dict):
        for key, value in data.items():
            if parent_key:
                new_key = f"{parent_key}.{key}"
            else:
                new_key = key
            explore_json_structure(value, new_key)
    elif isinstance(data, list):
        for index, item in enumerate(data):
            new_key = f"{parent_key}[{index}]"
            explore_json_structure(item, new_key)
    else:
        if parent_key:
            print(f"Key: {parent_key}, Value: {data}")
        else:
            print(f"Value: {data}")

# 以UTF-8编码打开JSON文件
with open("output.json", "r", encoding="utf-8") as file:
    json_data = json.load(file)

# 调用函数来探索JSON结构
explore_json_structure(json_data)

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值