0

Looking to create a function that will return a count of the number of occurences of a specified number in a file.

def countingNumber(num):

        infile = open('text.txt', 'r')
        contents = infile.read()

        count = 0


        for line in contents.split('\n'):
            if str(number) in line:
                count +=1


        return count

Everything works, but I am getting more than the desired number, so say for example that I want to search for the number 30 and type:

countingNumber(30)

I will also get a count of any lines that have the number 300 or 3000 in it. Is there a way to get unique numbers counts?

2 Answers 2

1

Using Regex boundaries \b.

Ex:

def countingNumber(num):
    count = 0
    with open('text.txt') as infile:
        for line in infile:
            if re.search(r"\b{}\b".format(num), line):
                count += 1
        return count
Sign up to request clarification or add additional context in comments.

1 Comment

re.findall could be more direct. Either way, regex rocks. :)
0

Split the line into words (using split()), and then check if str(number) exists in the resulting array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.