|
import os, orjson |
|
import re |
|
|
|
cur_dir = os.path.dirname(os.path.abspath(__file__)) |
|
|
|
txt_dir = cur_dir + "/text" |
|
|
|
|
|
categories = os.listdir(txt_dir) |
|
|
|
def parse_speech(text): |
|
|
|
speaker_pattern = re.compile(r'<SPEAKER ID=\"\d+\" NAME=\"(.*?)\"') |
|
|
|
output = [] |
|
speaker_name = "" |
|
|
|
for line in text.split('\n'): |
|
|
|
if '<SPEAKER' in line: |
|
|
|
match = speaker_pattern.search(line) |
|
if match: |
|
speaker_name = match.group(1) |
|
|
|
elif '<P>' in line or '<CHAPTER ID=' in line: |
|
continue |
|
|
|
else: |
|
|
|
if speaker_name: |
|
formatted_line = f"\n{speaker_name}: {line}" |
|
|
|
speaker_name = "" |
|
else: |
|
formatted_line = line |
|
output.append(formatted_line) |
|
|
|
return "\n".join(output) |
|
|
|
for category in categories: |
|
|
|
files = os.listdir(txt_dir + category) |
|
|
|
jsonl_docs = [] |
|
for file in files: |
|
|
|
with open(txt_dir + category + "/" + file, "r") as f: |
|
|
|
try: |
|
content = f.read() |
|
|
|
parsed_content = parse_speech(content) |
|
|
|
jsonl_docs.append({"text": parsed_content, "lang": category}) |
|
except: |
|
print("Error reading file:", file) |
|
continue |
|
|
|
|
|
with open(cur_dir + "/jsonl/" + category + ".jsonl", "wb") as f: |
|
for doc in jsonl_docs: |
|
f.write(orjson.dumps(doc) + b"\n") |
|
|
|
|