如何在文本文件中查找序列

时间:2015-01-10 15:17:30

标签: python python-3.x

你能解释一下如何在Python3的文本文件中找到序列吗?

例如我有文本文件:

1
2
3
3
3
1
2
2
4

现在,例如,我想计算这个文件中有多少'3'序列(在这个例子中有一个序列3,3,3)。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用Counter

的test.txt:

1
2
3
3
3
4
4
5
6
7
8
8
8
8
9
假设某个序列只能出现一次

from collections import Counter  

with open('test.txt' ,'r') as f:
    sequences = Counter(f.read().replace("\n", ""))


for seq, count  in sequences.items():
    if count > 1:
        print('number {} appears {} times'.format(seq, count))

输出:

number 4 appears 2 times
number 3 appears 3 times
number 8 appears 4 times
相关问题