Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Python中的文本文件返回特定/唯一数字的计数?_Python_Python 3.x - Fatal编程技术网

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

从Python中的文本文件返回特定/唯一数字的计数?,python,python-3.x,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 +

希望创建一个函数,该函数将返回文件中指定数字的出现次数计数

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?

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

使用正则表达式边界
\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

re.findall
可以更直接。无论哪种方式,regex rocks.:)