如何使用 Python 计算文件中“1 1”、“-1 1”、“1 -1”和“-1 -1”的出现次数?

How to count occurrences of "1 1", "-1 1", "1 -1", and "-1 -1" in a file using Python?

我的数据文件包含以下格式的值:

1 1
-1 1
1 -1
-1 -1
...

每次我注意到这些发生时,我都需要计算一个变量的增量。例如遇到1 -1PositiveNegative += 1,遇到-1 -1NegativeNegative += 1

到目前为止我有这个:

PositivePositive = 0
f1 = open("200_sample.txt", 'r')
v = f1.read()
for line in v:
    if "1 1" in line:
        PositivePositive +=1

但它不计算 1 1 的任何出现。有什么建议吗?

当您执行 v = f1.read() 时,会将文件的所有内容读入一个长字符串,称为 v。当您使用 for line in v: 对其进行迭代时,它一次查看一个 单个字符 。所以,当然,它不会在一个字符中找到三个字符。

要解决此问题,只需不要 read() 文件对象即可。直接遍历即可,文件reader会逐行遍历:

lines = {'-1 1':0, '1 -1':0, '1 1':0, '-1 -1':0}
with open("200_sample.txt", 'r') as f:
    for line in f:
        lines[line.strip()] += 1

此外,使用 with 上下文管理器在该块结束后自动关闭文件。

您可以将每种行存储为字典键,然后在看到它时更新该键的值。

您可以使用带有 for 循环的默认字典

from collections import defaultdict

myfile = open("thefile.txt")

mycountdict = defaultdict(lambda: 0)

for line in myfile.readlines():
    mycountdict[line] += 1

然后 printreturn defaultdict

所需的输出
print(mycountdict["1 1\n"])