提问人:Artemis 提问时间:11/13/2023 最后编辑:Artemis 更新时间:11/13/2023 访问量:79
从方法中返回一个值,并将其重新用于类中的下一个方法
Return a value from a method and re-use it to the next method inside class
问:
我正在尝试理解类和方法。
假设我们有一个自定义类,它有 3 种方法,允许我:Nlkt_custom
- 读取文本文件
- 标记文本
- 返回单词出现次数
返回 并稍后定义它们,以便将其输出用于下一个方法是否是一种好的做法?如果不是,构建这些方法的首选方法是什么?fic
words
sorted_freqs
class Nltk_custom:
_defaultEncoding = "utf-8"
_defaultLang = "english"
def __init__(self, filename, encoding=_defaultEncoding, lang=_defaultLang):
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, fic):
words = nltk.tokenize.word_tokenize(fic.lower(), self.lang)
return words
def sort_frequences(self, dictionnaire):
# I am using it again in other methods, so I decided to create a function apart
return dict(sorted(dictionnaire.items(), key=lambda item: item[1], reverse=True))
def custom_frq(self, words):
freqs = FreqDist(words)
sorted_freqs = self.sort_frequences(freqs)
return sorted_freqs
fic_inst = Nltk_custom(filename="arandomfile.txt")
fic = fic_inst.custom_read()
words = fic_inst.custom_tokenisation(fic)
#words = Nltk_custom.custom_tokenisation(fic)
sorted_freqs = fic_inst.custom_frq(words)
答:
1赞
quamrana
11/13/2023
#1
您应该以不同的方式编写最后两个方法,并使用适当的参数调用它们:
class Nltk_custom:
... # other methods elided
def custom_tokenisation(self, fic):
words = nltk.tokenize.word_tokenize(fic.lower(), self.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)
请注意最后两个方法的 how 和 are 参数。fic
words
评论
0赞
jonrsharpe
11/13/2023
也应该如此,但这是任一方法中对实例状态的唯一引用。self.lang
0赞
quamrana
11/13/2023
@jonrsharpe:好地方。我会解决这个问题。但是,这意味着 OP 从未尝试运行代码:-(
0赞
Artemis
11/13/2023
谢谢。我没有正确使用实例。使用 和 作为最后两种方法的参数是一种好的做法吗?fic
words
0赞
quamrana
11/13/2023
是的,将参数传递到方法中而不是依赖全局变量是一个更好的主意。
0赞
Artemis
11/13/2023
@quamrana我运行了代码,但我省略了之前+之后的一些部分。打错了对不起。通过分配会导致什么问题?self=fic
评论
Nltk_custom
sorted_freqs = Nltk_custom.custom_frq(words)
words
words
words = Nltk_custom.custom_tokenisation(fic) and sorted_freqs = Nltk_custom.custom_frq(words)