簡體   English   中英

Python中的文件中計數的字符串

[英]Counting a string within a file in python

我有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

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)之后不需要該代碼。

考慮:

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執行'123' in some_file_as_string有點浪費,因為它仍然需要遍歷整個字符串。 您還是應該進行計數,然后在計數返回大於0時執行一些操作。

你也有這個

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

詢問是否存在字符串“ z”,您應該改為檢查變量z (不帶引號)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM