简体   繁体   中英

Defining a function to count the number of lines in a file, containing a certain substring

I'm kinda new to Python. I'm trying to define a function that can count the number of lines in a file, containing a particular substring. I also want to count the lines which have multiple values of my substring as just 1.

Here's my code:

def CLT(filename):
    with open(filename,'r') as f:
        pattern='ing'
        count=a=0
        k=f.readlines()
        for line in k:
            if pattern in k[a:]:
                count += 1
        return count

print( CLT('random_file.txt') )

Assume that my file has 25 instances where a string 'str' appears but it has 2 lines where 2 'str' appear on the same line. So the ideal output to this problem should be 23.

But its returning 0 as the number of lines. I also recognize that my code doesn't do the part where the lines with multiple substrings will be counted as just 1 count. What can I do to improve this code?

Here is the code you might want to try,

def CLT(filename):
    with open(filename, 'r') as f:
        pattern = 'ing'
        count = 0
        for line in f:
            if pattern in line:
                count += 1
        return count


print(CLT('random_file.txt'))

Hope this helps you!

You've got a slight error in your code:

if pattern in k[a:]:

should be:

if pattern in line[a:]:

It looks like you're positioning yourself to use a to keep track of when you've already found the string in the line and you're now looking for an additional occurrence, but if not, you should remove it as it complicates the logic.

Otherwise, if you use a to show the index of where you already found an occurrence of the string in the line, you need to make sure to start looking again at index a + 1 so that you don't find the same occurrence again and again and end up in an infinite loop when you add a loop to check for further occurrences in the same line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM