From d743ed2567f8aa5c28f72d4ba87be33708ae4793 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 4 Nov 2024 17:20:03 +0100 Subject: [PATCH] Joined rename_topics and name_topics methods together --- turftopic/base.py | 27 +++++++++++---------------- turftopic/models/decomp.py | 2 +- 2 files changed, 12 insertions(+), 17 deletions(-) diff --git a/turftopic/base.py b/turftopic/base.py index 86bb7cc..084be16 100644 --- a/turftopic/base.py +++ b/turftopic/base.py @@ -84,19 +84,7 @@ def _top_terms( terms.append(list(vocab[highest])) return terms - def name_topics(self, namer: TopicNamer) -> list[str]: - """Names topics with a topic namer in the model. - - Parameters - ---------- - namer: TopicNamer - A Topic namer model to name topics with. - - Returns - ------- - list[str] - List of topic names. - """ + def _rename_automatic(self, namer: TopicNamer) -> list[str]: self.topic_names_ = namer.name_topics(self._top_terms()) return self.topic_names_ @@ -366,14 +354,19 @@ def topic_names(self) -> list[str]: names.append(f"{topic_id}_{concat_words}") return names - def rename_topics(self, names: Union[list[str], dict[int, str]]) -> None: - """Rename topics in a model manually. + def rename_topics( + self, names: Union[list[str], dict[int, str], TopicNamer] + ) -> None: + """Rename topics in a model manually or automatically, using a namer. Examples: ```python model.rename_topics(["Automobiles", "Telephones"]) # Or: model.rename_topics({-1: "Outliers", 2: "Christianity"}) + # Or: + namer = OpenAITopicNamer() + model.rename_topics(namer) ``` Parameters @@ -381,7 +374,9 @@ def rename_topics(self, names: Union[list[str], dict[int, str]]) -> None: names: list[str] or dict[int,str] Should be a list of topic names, or a mapping of topic IDs to names. """ - if isinstance(names, dict): + if isinstance(names, TopicNamer): + self._rename_automatic(names) + elif isinstance(names, dict): topic_names = self.topic_names for topic_id, topic_name in names.items(): try: diff --git a/turftopic/models/decomp.py b/turftopic/models/decomp.py index d00d60d..41ff157 100644 --- a/turftopic/models/decomp.py +++ b/turftopic/models/decomp.py @@ -145,7 +145,7 @@ def fit_transform( console.log("Model fitting done.") return doc_topic - def name_topics(self, namer: TopicNamer) -> list[str]: + def _rename_automatic(self, namer: TopicNamer) -> list[str]: """Names topics with a topic namer in the model. Parameters