def file_reading(file_name, search_string):
# this will put the contents of the file into a string
file1 = open(file_name, 'r')
file_contents = file1.read()
file1.close() # close the file
# return the number of times the string was found
return file_contents.count(search_string)
def file_reading(input_file, pattern):
with open(input_file, 'r') as text_file:
data = text_file.read()
matches = re.findall(pattern, data)
if matches:
print(matches) # prints a list of all strings found
您的代码有多个问题。你知道吗
首先,调用^{} 返回一个file对象。它不读取文件的内容。为此,您需要使用
read()
或遍历file对象。你知道吗其次,如果您的目标是计算字符串的匹配数,则不需要正则表达式。您可以使用字符串函数
count()
。即使如此,将正则表达式调用放在引号中也是没有意义的。你知道吗将字符串
"re.findall(pattern, file1.read())"
赋给变量match1
。你知道吗以下是一个适合您的版本:
有几个错误,让我们逐一检查:
"re.findall(pattern, file1.read())"
放在引号里就是一个字符串。如果你真的想打电话给关于芬德尔函数,不需要引号:)match1
是否为None,这非常好,但是应该返回匹配的,而不是初始模式。你知道吗此外:
with open(filename, action)
syntax。你知道吗所以,综合起来,它看起来是这样的(为了清晰起见,我更改了一些变量名):
您可以逐行读取,而不是读取整个文件,然后找到模式重复的次数,并将其添加到总计数
c
相关问题 更多 >
编程相关推荐