|
import os |
|
import re |
|
import sys |
|
import json |
|
import html |
|
|
|
MESSAGE_SPLIT_PATTERN = re.compile(r"\n--- (?=\d+ *\n)") |
|
REPLY_ID_PATTERN = re.compile(r">>(\d+)") |
|
|
|
def main(): |
|
for folder in os.listdir(): |
|
if not os.path.isdir(folder) or folder.startswith("."): |
|
continue |
|
board_result = [] |
|
for file in os.listdir(folder): |
|
if not file.endswith(".txt"): |
|
continue |
|
file = os.path.join(folder, file) |
|
if not os.path.isfile(file): |
|
continue |
|
with open(file, "r", encoding="utf8") as f: |
|
content = f.read()[5:] |
|
content = MESSAGE_SPLIT_PATTERN.split(content) |
|
result = [] |
|
orig_to_norm = {} |
|
i = 1 |
|
for message in content: |
|
message = message.strip() |
|
if not message: |
|
continue |
|
j = 0 |
|
message_content = "" |
|
message_has_content = False |
|
for line in message.split("\n"): |
|
line = line.strip() |
|
if j == 0: |
|
try: |
|
message_id = int(line) |
|
except Exception: |
|
raise RuntimeError(f"Failed to parse message ID for \"{line}\" in \"{file}\"!") |
|
orig_to_norm[message_id] = i |
|
else: |
|
replace_count = 0 |
|
def replace_id(match): |
|
nonlocal replace_count |
|
replace_count += 1 |
|
return f">>{orig_to_norm.get(int(match.group(1)), "unknown")}" |
|
line = html.unescape(REPLY_ID_PATTERN.sub(replace_id, line)) |
|
if not message_has_content and replace_count == 0 and line.strip(): |
|
message_has_content = True |
|
if j != 1: |
|
message_content += "\n" |
|
message_content += line |
|
j += 1 |
|
if j == 0: |
|
raise RuntimeError(f"This message \"{message}\" in \"{file}\" doesn't start with a message ID!") |
|
if not message_has_content: |
|
orig_to_norm.pop(message_id) |
|
continue |
|
result.append({"id": i, "content": message_content}) |
|
i += 1 |
|
board_result.append(result) |
|
with open(f"{folder}.json", "w", encoding="utf8") as f: |
|
json.dump(board_result, f, ensure_ascii=False) |
|
|
|
if __name__ == "__main__": |
|
try: |
|
main() |
|
except KeyboardInterrupt: |
|
print("\nScript interrupted by user, exiting...") |
|
sys.exit(1) |
|
|