File size: 1,670 Bytes
911a2c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python3
"""
Sort a JSONL file of cleaned man pages alphabetically by "id".
Usage:
    python sort_cleaned.py [input.jsonl] [output.jsonl]
Defaults:
    input  = cleaned_manuals.jsonl
    output = sorted_manuals.jsonl
"""

import json
import sys

def sort_cleaned(input_path: str, output_path: str):
    """Load records, sort by 'id', write sorted JSONL."""
    print(f"Loading {input_path} ...", file=sys.stderr)
    records = []

    with open(input_path, 'r', encoding='utf-8') as fin:
        for line_no, line in enumerate(fin, 1):
            line = line.strip()
            if not line:
                continue
            try:
                rec = json.loads(line)
                records.append(rec)
            except json.JSONDecodeError as e:
                print(f"Warning: bad JSON at line {line_no}: {e}", file=sys.stderr)

            if line_no % 10000 == 0:
                print(f"  loaded {line_no} records...", file=sys.stderr)

    print(f"Loaded {len(records)} records. Sorting...", file=sys.stderr)

    # Alphabetical sort by the "id" field
    records.sort(key=lambda x: x.get("id", ""))

    print(f"Writing sorted records to {output_path} ...", file=sys.stderr)
    with open(output_path, 'w', encoding='utf-8') as fout:
        for rec in records:
            fout.write(json.dumps(rec, ensure_ascii=False) + '\n')

    print("Done.", file=sys.stderr)


if __name__ == "__main__":
    # command‑line arguments or defaults
    input_file = sys.argv[1] if len(sys.argv) > 1 else "cleaned_manuals.jsonl"
    output_file = sys.argv[2] if len(sys.argv) > 2 else "sorted_manuals.jsonl"

    sort_cleaned(input_file, output_file)