我会用闭包吗?

2024-10-03 23:22:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我该如何模拟这个结果

>>> countthesewords = wordcounter("~/mybook.txt")
>>> countthesewords['coffee']
15

我猜你首先需要在def中做def

#filename is wordcountingprogram

def wordcounter(filename):
    txtfile = open(filename, 'r')
    txtstr = txtfile.read()
wordcounter = txtstr ?????

我想我应该把这个文件变成一个图书馆,但是我怎样才能得到它,这样你就可以这样称呼它?你知道吗

我知道了,谢谢你的帮助!你知道吗


Tags: 文件txtread图书馆isdefopenfilename
3条回答

不,您可以创建一个名为classwordcounter(大写的Wordcounter更符合PEP-8)并重载__getitem__方法。下面是一个例子,让您了解这个想法:

class Wordcounter:
    def __init__(self, filename):
        f = open(filename, 'r')
        self.s = f.read()

    def __getitem__(self, item):
        return self.s.count(item)

w = Wordcounter('testfile.txt')
print w['coffee']

结果:

15

详见Python data model documentation

不,函数中不需要函数。尝试使用collections模块中的Counter类。你知道吗

from collections import Counter

def wordcounter(filename):
    with open(filename) as txtfile: # Make sure file is taken care of
        word_count = Counter(txtfile.read().split())

    return word_count

除了@Selcuk的建议之外,使用len(string)来计算:

import re

def wordcounter(filename, word):
   txtfile = open(filename, 'r')
   text = txtfile.read()
   repetition = re.findall(word, text)
   print len(repetition)

wordcounter('file.txt', 'coffee')

相关问题 更多 >