Skip to content Skip to sidebar Skip to footer

Counting Number Of Times A Group Of String Have Occurred And Print The String And Number Of Occurrence In Python 2.7

I am trying to read a text file line by line and check the number of occurrence of each group of strings in a line for example. A text file contains these lines (Which varies) X_0

Solution 1:

You can achieve this by using the Counter container from the collection module. From the Python documentation: "A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages."

Here is a sample code that does what you are asking for. I used the fact that a file is an iterator to create the Counter object. When you iterate, on a file it yields each line but does not remove the newline character so I used the strip() method to get the output you suggested.

filename = 'test.txt'

filetxt = """\
X_0_Gui_Menu_400_Menu_System
X_0_Gui_Menu_400_Menu_System
X_0_Gui_Menu_000_Menu_root
X_0_Gui_Menu_000_Menu_root
X_0_Gui_Menu_000_Menu_root
X_0_Gui_Menu_300_Menu_Outputs
X_0_Gui_Menu_300_Menu_Outputs
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
"""withopen(filename, 'w') as f:
    f.write(filetxt)

from collections import Counter
withopen(filename, 'r') as f:
    c = Counter(f)

# use iteritems() in python 2.7 instead of itemsfor key, value in c.items():
    print(key.strip())
    print('{:d} times'.format(value))

Solution 2:

file = open('test.txt')
fileLines = file.read().split('\n')
list = []

for line in fileLines :
    for tup in list:
        if tup[0] == line:
                list[list.index(tup)][1] = list[list.index(tup)][1] + 1breakelse:
        list.append([line, 1])

for s in list:
    print(s[0] + ' ' + str(s[1]))

This should read the lines in the file. If the line does not exist in list, then it adds a tuple to the list consisting of the string and the count. If the line does exist, then it just adds 1 to the count in the appropriate tuple.

Post a Comment for "Counting Number Of Times A Group Of String Have Occurred And Print The String And Number Of Occurrence In Python 2.7"