Python从一个类方法中获取结果并将其输入到另一个类方法中
这个问题是为了学习,没有什么实际用途。Python从一个类方法中获取结果并将其输入到另一个类方法中,python,oop,Python,Oop,这个问题是为了学习,没有什么实际用途。 TextStat是一个类,它有一个方法count\u words,该方法读取文本文件,并提供从最频繁的单词到最不频繁的单词排序的单词频率(单词计数)字典 import pandas as pd from collections import Counter from itertools import chain class TextStat: def __init__(self, file_path): self.file_pat
TextStat
是一个类,它有一个方法count\u words
,该方法读取文本文件,并提供从最频繁的单词到最不频繁的单词排序的单词频率(单词计数)字典
import pandas as pd
from collections import Counter
from itertools import chain
class TextStat:
def __init__(self, file_path):
self.file_path = file_path
def count_words(self):
with open(self.file_path, encoding='utf-8') as file:
text = [line.split() for line in file.readlines()]
text = list(chain(*text))
dict_text = dict(Counter(text))
dict_text = dict(sorted(dict_text.items(), key=lambda item: item[1], reverse=True))
return dict_text
示例:
text_1 = TextStat('path/to/file')
dict_1 = text_1.count_words()
问题
我们如何改进这个类,给它另一个方法dict_to_df
,它从count_words
方法中获取输出字典,而不直接调用count_words
;如果我们想的话,我们可以得到一个熊猫数据帧
def dict_to_df(dic):
'''Given a dictionary; give a pandas Dataframe.'''
df = pd.DataFrame(data={'WORD': dic.keys(), 'FREQ': dic.values()})
return df
我的意思是,用户应该能够在不调用文本\u 1.count\u words()
的情况下执行以下操作:
dict_1
应在类内创建,而不受用户的干扰。code
text_1 = TextStat('path/to/file')
dict_1 = text_1.count_words() # As dictionary
df1 = text_1.dict_to_df() # As DataFrame
尽可能地重用操作代码
import pandas as pd
from collections import Counter
from itertools import chain
class TextStat:
def __init__(self, file_path):
self.file_path = file_path
def count_words(self):
with open(self.file_path, encoding='utf-8') as file:
text = [line.split() for line in file.readlines()]
text = list(chain(*text))
dict_text = dict(Counter(text))
dict_text = dict(sorted(dict_text.items(), key=lambda item: item[1], reverse=True))
return dict_text
def dict_to_df(self):
dic = self.count_words() # self refers to object instance and we
# gain access to its methods
df = pd.DataFrame(data={'WORD': dic.keys(), 'FREQ': dic.values()}) # using your method
return df
用法
text_1 = TextStat('path/to/file')
dict_1 = text_1.count_words() # As dictionary
df1 = text_1.dict_to_df() # As DataFrame
不清楚你在问什么。如果他们没有呼叫
count\u words
,他们从哪里得到dict\u 1
。您也可以通过调用count\u words
本身来定义一个直接从TextStat
实例到数据帧的方法。@chpner类应该有两个方法;一个给我们一本字典,另一个给我们一个数据框。。。但是,如果没有字典,pandas Dataframe无法创建,但是字典的创建应该由类完成,而不是由用户完成。我也不清楚。为什么不在TextStat类中使用签名dict\u to\u df(self)
使dict\u to\u df成为另一个方法呢。然后它可以调用count_单词本身来生成字典。然后用户只需使用:df1=text\u 1.dict\u to\u df()
@darryg,你的答案似乎是正确的,我没有想到,作为python和oop的初学者@阿克巴侯赛因——很高兴它有用。你知道如何使方法dict_to_df吗?