我将如何模仿此结果
>>> countthesewords = wordcounter("~/mybook.txt")
>>> countthesewords['coffee']
15
我猜你首先需要在def中进行def,
#filename is wordcountingprogram
def wordcounter(filename):
txtfile = open(filename, 'r')
txtstr = txtfile.read()
wordcounter = txtstr ?????
我想我应该将文件转换成一个库,但是如何获取它以便你可以这样调用呢?
我明白了,感谢所有帮助过的人!
答案 0 :(得分:4)
不,你不需要函数中的函数。尝试使用集合模块中的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
答案 1 :(得分:1)
不,你可以做的是创建一个名为class
的{{1}}(大写的Wordcounter会更符合PEP-8)并重载wordcounter
方法。这是一个让你了解这个想法的例子:
__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']
有关详细信息,请参阅Python data model documentation
答案 2 :(得分:0)
除了@ Selcuk的建议外,请使用len(字符串)来计算:
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')