从方法返回一个值并将其重新用于类内的下一个方法

问题描述 投票:0回答:1

我正在尝试理解类和方法。

假设我们有一个名为

Nlkt_custom
的自定义类,它有 3 个方法,允许我:

  1. 读取文本文件
  2. 对文本进行标记化
  3. 返回单词出现次数

返回

fic
words
sorted_freqs
并稍后定义它们,以便将它们的输出用于下一个方法,这是一个好习惯吗?如果没有,构建这些方法的首选方式是什么?

class Nltk_custom:
    _defaultEncoding = "utf-8"
    
    def __init__(self, filename, encoding=_defaultEncoding, lang="english"):
        self.filename = filename
        self.encoding = encoding
        self.lang = lang

    def custom_read(self):
        try:
            with open(self.filename, mode='r', encoding=self.encoding) as f:
                fic = f.read()
                return fic
        except FileNotFoundError:
            print(f"File '{self.filename}' not found.")
        return None

    def custom_tokenisation(self):
        words = nltk.tokenize.word_tokenize(fic.lower(), lang)
        return words

    def custom_frq(self):
        freqs = FreqDist(words)
        sorted_freqs = dict( sorted(freqs.items(), key=lambda item: item[1], reverse=True))
        return sorted_freqs


fic_inst = Nltk_custom(filename="arandomfile.txt")
fic = fic_inst.custom_read()
words = Nltk_custom.custom_tokenisation(fic)
sorted_freqs = Nltk_custom.custom_frq(words)

python nltk
1个回答
0
投票

您应该以不同的方式编写最后两个方法,并使用适当的参数调用它们:

class Nltk_custom:
    ...  # other methods elided

    def custom_tokenisation(self, fic):
        words = nltk.tokenize.word_tokenize(fic.lower(), lang)
        return words

    def custom_frq(self, words):
        freqs = FreqDist(words)
        sorted_freqs = dict( sorted(freqs.items(), key=lambda item: item[1], reverse=True))
        return sorted_freqs


fic_inst = Nltk_custom(filename="arandomfile.txt")
fic = fic_inst.custom_read()
words = fic_inst.custom_tokenisation(fic)
sorted_freqs = fic_inst.custom_frq(words)

注意

fic
words
现在是最后两个方法的参数。

© www.soinside.com 2019 - 2024. All rights reserved.