mrp*_*opo 5 python comparison file count
我有一份文本文件格式为:
-1+1
-1-1
+1+1
-1-1
+1-1
...
Run Code Online (Sandbox Code Playgroud)
我想要一个程序来计算有多少行有-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
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,它总是返回0,我不知道为什么.
任何帮助都会让我非常感激,因为我已经看了好几个小时!!
Mar*_*ers 16
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
Run Code Online (Sandbox Code Playgroud)
最重要的是,在计算线条时,删除空格(特别是换行符,但任何其他空格或制表符也可能会干扰).