在python中计算文件中的字符串

在python中计算文件中的字符串,python,string,Python,String,我有10个文件,其中包含100个名为randomnumbers(1-10).py的随机数。我想创建一个程序,当发现一个123的字符串时,它会说“恭喜”,并计算123出现的次数。我有“恭喜”部分,我为计数部分编写了代码,但结果总是为零。怎么了 for j in range(0,10): n = './randomnumbers' + str(j) + '.py' s='congradulations' z='123' def replacemachine(n, z, s):

我有10个文件,其中包含100个名为randomnumbers(1-10).py的随机数。我想创建一个程序,当发现一个123的字符串时,它会说“恭喜”,并计算123出现的次数。我有“恭喜”部分,我为计数部分编写了代码,但结果总是为零。怎么了

for j in range(0,10):
n = './randomnumbers' + str(j) + '.py'          
s='congradulations' 
z='123' 
def replacemachine(n, z, s):
    file = open(n, 'r')             
    text=file.read()    
    file.close()    
    file = open(n, 'w') 
    file.write(text.replace(z, s))
    file.close()
    print "complete"
replacemachine(n, z, s) 
count = 0
if 'z' in n:
    count = count + 1
else:
    pass
print count

如果n
中的'z'正在测试文本字符串
'z'
是否在文件名
n
中。由于只在
replacemachine
中打开文件,因此无法从外部访问文件内容

最好的解决方案是只从
replacemachine
中计算出现的次数:

def replacemachine(n, z, s):
    file = open(n, 'r')
    text=file.read()
    file.close()
    if '123' in text:
        print 'number of 123:', text.count('123')
    file = open(n, 'w')
    file.write(text.replace(z, s))
    file.close()
    print "complete"
那么在
替换机器(n,z,s)
之后您就不需要该代码了,请考虑:

some_file_as_string = """\
184312345294839485949182
57485348595848512493958123
5948395849258574827384123
8594857241239584958312"""

num_found = some_file_as_string.count('123')
if num_found > 0:
    print('num found: {}'.format(num_found))
else:
    print('no matches found')
在某些文件中作为字符串执行
'123'有点浪费,因为它仍然需要查看整个字符串。您也可以进行计数,并在计数返回大于0时执行某些操作

你也有这个

if 'z' in n:
    count = count + 1
else:
    pass
print count
它询问字符串“z”是否存在,您应该检查变量(不带引号)