从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.:)