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

时间:2012-07-18 15:18:16

标签: 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):
    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

2 个答案:

答案 0 :(得分:0)

if 'z' in n正在测试文字字符串'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"

然后在replacemachine(n, z, s)之后不需要该代码。

答案 1 :(得分:0)

考虑:

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' in some_file_as_string有点浪费,因为它仍然需要查看整个字符串。无论如何,当计数返回超过0时,你也可以做点什么。

你也有这个

if 'z' in n:
    count = count + 1
else:
    pass
print count

在询问字符串'z'是否存在时,您应该检查变量z(不带引号)

相关问题