From 314dff495d03552559eed166ca08f64a7e3d9dbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABl=20de=20Chalendar?= Date: Sat, 28 Nov 2026 23:31:58 +0100 Subject: [PATCH] Doc.save_conllu; lima command writes CoNLL-U with metadata (#8) Doc.save_conllu(path, doc_id=None) saves to_conllu() to a UTF-8 file with Unix line endings. to_conllu(doc_id) adds a "# newdoc id" comment and "-" sentence ids, unique in a file of several documents; the default output is unchanged. The lima command writes CoNLL-U with the metadata comments instead of repr(doc), to stdout or -o/--output. Co-Authored-By: Claude Opus 5.5 --- CHANGES.md | 10 ++++++++++ README.md | 1 + aymara/lima.py | 46 +++++++++++++++++++++++++++++++++++++------- tests/test_aymara.py | 22 +++++++++++++++++++++ 4 files changed, 72 insertions(+), 7 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index b810b1e..1a5910c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -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 `-`, 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. diff --git a/README.md b/README.md index ec7ae80..f50855a 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/aymara/lima.py b/aymara/lima.py index 105d4cf..31248ea 100644 --- a/aymara/lima.py +++ b/aymara/lima.py @@ -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 = " comment before the + first sentence and sentence ids "-" instead of "", 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 @@ -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), @@ -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, @@ -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) diff --git a/tests/test_aymara.py b/tests/test_aymara.py index 8ba9b2e..e755948 100644 --- a/tests/test_aymara.py +++ b/tests/test_aymara.py @@ -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()