Europarl-Conversation / build_europarl_conversation.py
m8than's picture
dataset upload
7402d25
import os, orjson
import re
cur_dir = os.path.dirname(os.path.abspath(__file__))
txt_dir = cur_dir + "/text"
# read folder names in /txt
categories = os.listdir(txt_dir)
def parse_speech(text):
# This pattern matches speaker tags and extracts ID and NAME attributes
speaker_pattern = re.compile(r'<SPEAKER ID=\"\d+\" NAME=\"(.*?)\"')
# Initialize variables
output = []
speaker_name = ""
for line in text.split('\n'):
# Check for speaker tag
if '<SPEAKER' in line:
# Extract speaker name
match = speaker_pattern.search(line)
if match:
speaker_name = match.group(1)
# Check for paragraph tag or chapter id tag and skip it
elif '<P>' in line or '<CHAPTER ID=' in line:
continue
# Process normal text lines
else:
# Append speaker name before the speech if it's not empty
if speaker_name:
formatted_line = f"\n{speaker_name}: {line}"
# Reset speaker name to avoid repeating it for subsequent lines of the same speaker
speaker_name = ""
else:
formatted_line = line
output.append(formatted_line)
return "\n".join(output)
for category in categories:
# list txt files in each folder
files = os.listdir(txt_dir + category)
jsonl_docs = []
for file in files:
# read each txt file
with open(txt_dir + category + "/" + file, "r") as f:
# try to read content
try:
content = f.read()
parsed_content = parse_speech(content)
jsonl_docs.append({"text": parsed_content, "lang": category})
except:
print("Error reading file:", file)
continue
# write to jsonl file in jsonl folder
with open(cur_dir + "/jsonl/" + category + ".jsonl", "wb") as f:
for doc in jsonl_docs:
f.write(orjson.dumps(doc) + b"\n")