简体   繁体   English

Python:如何计算文件中的多少行相同

[英]Python: How to count how many lines in a file are the same

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. 我想有一个程序来计算有-1 + 1行和+ 1-1行的行数。 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. 但是由于某种原因,它总是返回0,我不知道为什么。

Any help would me much appreciated as I have been looking at this for hours!! 任何帮助我都会很感激,因为我已经看了几个小时了!!

Use collections.Counter instead: 使用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

Most of all, remove whitespace (the newline specifically, but any other spaces or tabs might interfere too) when counting your lines. 最重要的是,在计算行数时,请删除空格(特别是换行符,但其他空格或制表符也可能会干扰)。

.readlines()\\n .readlines()中,这就是为什么它们不匹配的原因。

If you don't want to import a module, enjoy short code, and like a bit of 'list' comprehension : 如果您不想导入模块,请享受简短的代码,并喜欢一点“列表”理解:

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

Then of course access counts as a dict 那么,当然可以counts访问视为命令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM