Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Changes

## Unreleased

* `Doc.save_conllu(path, doc_id=None)` (#8): saves the document to a CoNLL-U
file (UTF-8, Unix line endings) with its `# sent_id` and `# text` comments.
`Doc.to_conllu(doc_id=None)`: with a document id, a `# newdoc id` comment
and sentence ids `<doc_id>-<n>`, unique in a file of several documents.
* `lima` command: writes CoNLL-U with the metadata comments (`to_conllu`)
instead of `repr(doc)`, to the standard output or to `-o/--output`; with
several input files, each one's name is its document id.

## 0.11.0 - 20261128

Built on LIMA 3.2.0.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ hello
2 , , PUNCT _ _ 1 punct _ Pos=5|Len=1
3 World World PROPN _ Number:Sing 1 vocative _ Pos=7|Len=5
4 ! ! PUNCT _ _ 1 punct _ Pos=12|Len=1
>>> doc.save_conllu("hello.conllu") # with the "# sent_id" and "# text" comments
```

`lima_models -i eng` installs the default English model, which
Expand Down
46 changes: 39 additions & 7 deletions aymara/lima.py
Original file line number Diff line number Diff line change
Expand Up @@ -1163,18 +1163,25 @@ def to_spacy(self, vocab=None):
from aymara.lima_spacy import doc_to_spacy
return doc_to_spacy(self, vocab)

def to_conllu(self) -> str:
def to_conllu(self, doc_id: Optional[str] = None) -> str:
"""The document in CoNLL-U format: a "# sent_id" and a "# text" comment per
sentence, word ids from 1 in each sentence, SpaceAfter=No, and an N-M
line for the words of a multiword token sharing its position (French
"du" -> "de" "le"). Doc.from_conllu reads it back.

:param doc_id: if given, a "# newdoc id = <doc_id>" comment before the
first sentence and sentence ids "<doc_id>-<n>" instead of "<n>", which
keeps the ids unique when several documents go in the same file
:return: the CoNLL-U text, ending with an empty line
"""
lines = []
text = self.text
if doc_id is not None:
doc_id = " ".join(str(doc_id).split())
lines.append(f"# newdoc id = {doc_id}")
for n, sent in enumerate(self.sents, start=1):
lines.append(f"# sent_id = {n}")
lines.append(f"# sent_id = {n}" if doc_id is None
else f"# sent_id = {doc_id}-{n}")
lines.append("# text = " + " ".join(sent.text.split()))
tokens = list(sent)
k = 0
Expand Down Expand Up @@ -1207,6 +1214,17 @@ def to_conllu(self) -> str:
lines.append("")
return "\n".join(lines) + "\n"

def save_conllu(self, path: Union[str, os.PathLike],
doc_id: Optional[str] = None) -> None:
"""Save the document to a CoNLL-U file, with the metadata comments of
to_conllu (sentence ids and texts), in UTF-8 with Unix line endings.

:param path: the file to write (replaced if it exists)
:param doc_id: the document id, see to_conllu
"""
with open(path, "w", encoding="utf-8", newline="\n") as conllu_file:
conllu_file.write(self.to_conllu(doc_id))

@classmethod
def from_conllu(cls, conllu: str, lang: str = "") -> "Doc":
"""A document from a CoNLL-U text (e.g. a UD treebank's, or to_conllu's),
Expand Down Expand Up @@ -2197,6 +2215,13 @@ def main(): # pragma: no cover
default="",
help="set the user resources path to use",
)
parser.add_argument(
"-o",
"--output",
type=str,
default="",
help="the CoNLL-U file to write (default: the standard output)",
)
parser.add_argument(
"file",
type=str,
Expand All @@ -2215,11 +2240,18 @@ def main(): # pragma: no cover
user_config_path=args.config_path,
user_resources_path=args.resources_path,
meta=metadata)
for file_name in tqdm(args.file):
with open(file_name) as text_file:
text = text_file.read()
r = nlp(text)
print(repr(r))
# A document id per file when there are several, to keep sent_id unique
several = len(args.file) > 1
out = (open(args.output, "w", encoding="utf-8", newline="\n") if args.output
else sys.stdout)
try:
for file_name in tqdm(args.file):
with open(file_name, encoding="utf-8") as text_file:
doc = nlp(text_file.read())
out.write(doc.to_conllu(file_name if several else None))
finally:
if out is not sys.stdout:
out.close()
sys.exit(0)


Expand Down
22 changes: 22 additions & 0 deletions tests/test_aymara.py
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,28 @@ def test_from_conllu_ud():
assert "\n3-4\tdu\t" in out


def test_save_conllu(tmp_path):
conllu = ("# sent_id = 1\n# text = Il vient.\n"
"1\tIl\til\tPRON\t_\t_\t2\tnsubj\t_\t_\n"
"2\tvient\tvenir\tVERB\t_\t_\t0\troot\t_\tSpaceAfter=No\n"
"3\t.\t.\tPUNCT\t_\t_\t2\tpunct\t_\t_\n\n"
"# sent_id = 2\n# text = Été.\n"
"1\tÉté\tété\tNOUN\t_\t_\t0\troot\t_\tSpaceAfter=No\n"
"2\t.\t.\tPUNCT\t_\t_\t1\tpunct\t_\t_\n\n")
fdoc = aymara.lima.Doc.from_conllu(conllu, lang="ud-fra")
expected = fdoc.to_conllu()
path = tmp_path / "doc.conllu"
fdoc.save_conllu(path)
assert path.read_bytes() == expected.encode("utf-8") # no CRLF on Windows
fdoc.save_conllu(str(path), doc_id="d1")
saved = path.read_text(encoding="utf-8")
assert saved.split("\n")[:3] == ["# newdoc id = d1", "# sent_id = d1-1",
"# text = Il vient."]
assert "\n# sent_id = d1-2\n" in saved
back = aymara.lima.Doc.from_conllu(saved, lang="ud-fra")
assert back.text == fdoc.text and back.to_conllu() == expected


def test_span_as_doc():
# doc = lima("Give it back! He pleaded.")
sub = doc[4:7].as_doc()
Expand Down
Loading