def countsfunc(path, stri):
f = open('C:\Users....\sometextfile.txt','r')
dicts = {}
for line in f:
words = line.split()
dicts[words[1]] = dictst.get(words[0], 0) + 1
print countdict[word[0]]
f.close()
我做了一个函数,需要检查文本中每一行的第二个单词是否等于“stri”。但是我也想要这个函数计算它发生了多少次。 例如,文字就像:
老麦克唐纳有一个农场,E-I-E-I-O。 老麦克唐纳有一个农场,E-I-E-I-O。 老麦克唐纳有一个农场,E-I-E-I-O。这里有一个moo,有一个moo,到处都是moo moo
如果在shell中显示:
countsfunc(sometextfile, MacDonald)
然后它应该打印我“3”
如果:
countsfunc(sometextfile, a)
然后只是“1”
如果:
countsfunc(sometextfile, Mac)
然后是“0”。
编辑: 谢谢大家,我找到了解决方案。无论如何,谢谢
答案 0 :(得分:1)
def countsfunc(path, string):
counter = 0
with open(path) as f:
for line in f:
words = line.split()
if words[1] == string: #check if the second word is equal to string
counter+= 1
return counter
将文件路径和单词传递给函数。该功能将返回计数器编号。
答案 1 :(得分:0)
作为一个班轮:
def count_2nd_words(lines, match):
return sum(line.split()[1] == match for line in lines)
with open('C:\Users....\sometextfile.txt','r') as f:
print count_2nd_words(f, 'MacDonald')
答案 2 :(得分:0)
我的pythonic代码高尔夫版:
from collections import Counter
def countsfunc(path,string):
file = open(path,'r')
second_words = [line.rstrip().split(' ')[1] for line in file if line!='\n']
print Counter(second_words)[string]