60 lines
2.2 KiB
Python
60 lines
2.2 KiB
Python
import json
|
|
import argparse
|
|
from docx import Document
|
|
import os
|
|
import glob
|
|
|
|
def json_to_docx(input_paths, output_path, show_name):
|
|
document = Document()
|
|
|
|
for input_path in input_paths:
|
|
with open(input_path, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
for entry in data:
|
|
if show_name and 'name' in entry:
|
|
paragraph = document.add_paragraph()
|
|
paragraph.add_run(entry['name']).bold = True
|
|
paragraph.add_run('\n' + entry['message'])
|
|
else:
|
|
paragraph = document.add_paragraph(entry['message'])
|
|
|
|
document.save(output_path)
|
|
|
|
def get_json_files_from_directory(directory):
|
|
# 获取指定目录下所有的 JSON 文件
|
|
return glob.glob(os.path.join(directory, '*.json'))
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description='Convert JSON messages to DOCX format.')
|
|
parser.add_argument('input', nargs='+', help='Input JSON file paths or directory.')
|
|
parser.add_argument('-o', '--output', help='Output DOCX file path.', default=None)
|
|
parser.add_argument('-n', '--noname', action='store_true', help='Do not include name field in output.')
|
|
|
|
args = parser.parse_args()
|
|
|
|
input_files = []
|
|
|
|
for input_path in args.input:
|
|
if os.path.isdir(input_path):
|
|
# 如果是目录,则获取该目录下的所有 JSON 文件
|
|
input_files.extend(get_json_files_from_directory(input_path))
|
|
elif os.path.isfile(input_path) and input_path.endswith('.json'):
|
|
# 如果是单个文件,直接添加到列表
|
|
input_files.append(input_path)
|
|
|
|
if not input_files:
|
|
print("No JSON files found in the specified paths.")
|
|
return
|
|
|
|
if args.output is None:
|
|
# 如果没有指定输出路径,使用第一个输入路径并将扩展名改为 .docx
|
|
output_path = os.path.splitext(input_files[0])[0] + '.docx'
|
|
else:
|
|
output_path = args.output
|
|
|
|
json_to_docx(input_files, output_path, not args.noname)
|
|
print(f'DOCX file saved to: {output_path}')
|
|
|
|
if __name__ == '__main__':
|
|
main()
|