30 lines
1.1 KiB
Python
30 lines
1.1 KiB
Python
import json
|
|
import argparse
|
|
|
|
# 排序 JSON 文件
|
|
def sort_json_file(input_file, output_file, sort_key):
|
|
with open(input_file, 'r', encoding='utf-8') as f:
|
|
# 读取所有行并解析为 JSON
|
|
json_list = [json.loads(line.strip()) for line in f if line.strip()]
|
|
|
|
# 按指定键排序,从大到小
|
|
sorted_list = sorted(json_list, key=lambda x: int(x.get(sort_key, 0)), reverse=True)
|
|
|
|
# 写入排序后的结果到输出文件
|
|
with open(output_file, 'w', encoding='utf-8') as f:
|
|
for entry in sorted_list:
|
|
f.write(json.dumps(entry, ensure_ascii=False) + '\n')
|
|
|
|
print(f"排序完成!结果已保存到 {output_file}")
|
|
|
|
# 主函数
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(description="对 JSON 文件进行排序")
|
|
parser.add_argument("input_file", help="输入的 JSON 文件,每行一个 JSON 对象")
|
|
parser.add_argument("output_file", help="输出的排序结果文件")
|
|
parser.add_argument("sort_key", help="排序的键,比如 upload_date, view_count 等")
|
|
args = parser.parse_args()
|
|
|
|
sort_json_file(args.input_file, args.output_file, args.sort_key)
|
|
|
|
|