2012-07-18 43 views
0

我有10个文件,其中有100个随机数,名称为randomnumbers(1-10).py。我想创建一个程序,当找到123的字符串时,会显示“恭喜”,并计算出现123的次数。我有“祝贺”部分,并且已经编写了计数部分的代码,但我总是得到零。怎么了?在Python中计算文件中的字符串

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 
+0

我的回答有用吗? – 2012-10-02 17:01:46

回答

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)后的代码。

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.1

你也有这样的

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

这是询问是否字符串“Z”是存在,你应该检查z该变量改为(不含引号)