我该如何模拟这个结果
>>> countthesewords = wordcounter("~/mybook.txt")
>>> countthesewords['coffee']
15
我猜你首先需要在def中做def
#filename is wordcountingprogram
def wordcounter(filename):
txtfile = open(filename, 'r')
txtstr = txtfile.read()
wordcounter = txtstr ?????
我想我应该把这个文件变成一个图书馆,但是我怎样才能得到它,这样你就可以这样称呼它?你知道吗
我知道了,谢谢你的帮助!你知道吗
不,您可以创建一个名为
class
的wordcounter
(大写的Wordcounter更符合PEP-8)并重载__getitem__
方法。下面是一个例子,让您了解这个想法:结果:
详见Python data model documentation
不,函数中不需要函数。尝试使用collections模块中的Counter类。你知道吗
除了@Selcuk的建议之外,使用len(string)来计算:
相关问题 更多 >
编程相关推荐