ccel-paragraphs / parse.py
jncraton's picture
Upload parse.py
46e758c
raw
history blame
2.52 kB
import re
import os
import xml.etree.ElementTree as ET
def get_refs(root):
refs = []
for child in root:
if child.tag == 'scripRef':
if 'osisRef' in child.attrib:
refs.append(child.attrib['osisRef'])
return refs
def get_text_content(root, strip_ref=False):
""" Return the plain text content of a node
This will:
1. Remove all notes, footnotes, and references
2. Remove all newlines and combine whitespace to single spaces
"""
# Start with the root text prior to the first node
text = root.text or ""
for child in root:
if child.text:
if child.tag != 'scripRef' or not strip_ref:
text += child.text
if child.tail:
# Add the root node text between this child and the next child
text += child.tail
if strip_ref:
# Remove empty parens from removed references
text = re.sub(r"\([\n\t; ]*\)", " ", text)
# Combine whitespace to single space
# text = re.sub(r"[\n\t ]+", " ", text)
return text
def get_paras():
paras = []
from pathlib import Path
for filename in list(Path(".").rglob("*.xml")):
filename = str(filename)
if "authInfo." in filename:
continue
print(filename)
try:
tree = ET.parse(filename)
except:
print("ERROR: Unable to parse:", filename)
continue
root = tree.getroot()
#for i, p in enumerate(root.findall(".//p[scripRef]")):
for i, p in enumerate(root.findall(".//p")):
text = get_text_content(p)
if False:
text = re.sub(r'".*?"', '...', text, flags=re.M|re.DOTALL)
text = re.sub(r'“.*?”', '...', text, flags=re.M|re.DOTALL)
# Remove spaces before punctuation
text = re.sub(r"[\t\n ]\.", ".", text)
text = re.sub(r"[\t\n ],", ",", text)
# Combine elipses
text = re.sub(r"\.\.\.+", "...", text)
refs = get_refs(p)
if len(text) > 160 and 'id' in p.attrib:
yield {
"id": filename + ":" + p.attrib['id'],
"refs": refs,
"text": text,
"text-noref": get_text_content(p, strip_ref=True)
}
from datasets import Dataset
ds = Dataset.from_generator(get_paras)
ds.push_to_hub("jncraton/ccel-paragraphs")