[英]Python: How to count how many lines in a file are the same
我有一個文本文件,格式為:
-1+1
-1-1
+1+1
-1-1
+1-1
...
我想有一個程序來計算有-1 + 1行和+ 1-1行的行數。 然后,程序只需要返回這樣的幾行的值即可。 我已經寫了代碼:
f1 = open("results.txt", "r")
fileOne = f1.readlines()
f1.close()
x = 0
for i in fileOne:
if i == '-1+1':
x += 1
elif i == '+1-1':
x += 1
else:
continue
print x
但是由於某種原因,它總是返回0,我不知道為什么。
任何幫助我都會很感激,因為我已經看了幾個小時了!!
使用collections.Counter
代替:
import collections
with open('results.txt') as infile:
counts = collections.Counter(l.strip() for l in infile)
for line, count in counts.most_common():
print line, count
最重要的是,在計算行數時,請刪除空格(特別是換行符,但其他空格或制表符也可能會干擾)。
.readlines()
將\\n
.readlines()
中,這就是為什么它們不匹配的原因。
如果您不想導入模塊,請享受簡短的代碼,並喜歡一點“列表”理解:
with open('results.txt') as infile:
counts = { key: infile.count(key) for key in ['-1+1', '+1-1'] }
那么,當然可以counts
訪問視為命令
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.