count of occurances of string in file in python

You can use the re (regular expression) module and read the file line by line to count the occurrences of a specific string in a file. Here's an example code:

main.py
import re

# specify the file path
file_path = '/path/to/your/file.txt'

# specify the string to be searched
string_to_be_searched = 'example'

# initialize the counter
counter = 0

# open the file in read mode
with open(file_path, 'r') as file:
    # iterate through each line
    for line in file:
        # search for the string using regular expression
        matches = re.findall(string_to_be_searched, line)
        # update the counter
        counter += len(matches)

# print the count of occurrences
print(f"The string '{string_to_be_searched}' appears {counter} times in the file.")
594 chars
23 lines

In this code, we first import the re module. Then, we specify the file path and the string to be searched. We initialize the counter to zero.

Then, we use with open(file_path, 'r') as file to open the file and read it line by line. For each line, we search for the string using re.findall method, which returns a list of all non-overlapping matches of the regular expression in the string. We then update the counter by adding the length of this list.

Finally, we print the count of occurrences of the string in the file.

gistlibby LogSnag