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.py594 chars23 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