I have a text document in the format of:
-1+1
-1-1
+1+1
-1-1
+1-1
...
I want to have a program that counts how many lines have -1+1 lines and +1-1 lines. The program would then just need to return the value of how many lines are like this.
I have written the code:
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
But for some reason, it always returns 0 and I have no idea why.
Use collections.Counter
instead:
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
Most of all, remove whitespace (the newline specifically, but any other spaces or tabs might interfere too) when counting your lines.
The .readlines()
leaves the \n
in the lines, that's why they don't match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With