6

我有一个格式如下的文本文档:

-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,我不知道为什么。

4

3 回答 3

19

改用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

最重要的是,在计算行数时删除空格(特别是换行符,但任何其他空格或制表符也可能会干扰)。

于 2013-01-10T14:42:50.827 回答
8

.readlines()留在行中,这\n就是他们不匹配的原因。

于 2013-01-10T14:43:07.513 回答
0

如果您不想导入模块,请享受简短的代码,并喜欢一些“列表”理解:

with open('results.txt') as infile:
    counts = { key: infile.count(key) for key in ['-1+1', '+1-1'] }

然后当然可以counts作为 dict访问

于 2013-01-10T16:36:35.653 回答