从Python中的文本文件返回特定/唯一数字的计数?

时间:2019-06-12 17:07:42

标签: python python-3.x

试图创建一个函数,该函数将返回文件中指定次数出现次数的计数。

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

一切正常,但是我得到的数字超出了所需的数字,例如,假设我要搜索数字30并输入:

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 个答案:

答案 0 :(得分:1)

使用正则表达式边界\b

例如:

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

答案 1 :(得分:0)

使用split()将行分割成单词,然后检查结果数组中是否存在str(number)。