【发布时间】:2015-03-06 16:05:26
【问题描述】:
如果我有一个像下面这样的类(实际上,它有更多的方法),并且我想将每个方法的结果加载到字典中,有没有更快的方法来做features_to_dict,如果我添加新方法?
from bs4 import BeautifulSoup
class CraigsPage():
def __init__(self, page_file):
self._page = open(page_file).read()
self.soup = BeautifulSoup(self._page)
self.title = self.soup.title.string
self.body = str(self.soup.find('section', id='postingbody'))
def get_title_char_count(self):
return len(list(self.title.replace(' ', '')))
def get_title_word_count(self):
return len(self.title.split())
def get_body_char_count(self):
return len(list(self.body.replace(' ', '')))
def features_to_dict(self):
feature_dict = {}
feature_dict['title_char_count'] = self.get_title_char_count()
feature_dict['title_word_count'] = self.get_title_word_count()
feature_dict['body_char_count'] = self.get_body_char_count()
return feature_dict
【问题讨论】:
-
不要使用 get_ getter。使用属性。 docs.python.org/2/library/functions.html#property
-
这很有趣。我不知道那些。有什么方法可以自动加载所有这些?
标签: python class dictionary methods