擅长:python、mysql、java
<p>您的代码有多个问题。你知道吗</p>
<p>首先,调用<a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow noreferrer">^{<cd1>}</a>返回一个file对象。它不读取文件的内容。为此,您需要使用<code>read()</code>或遍历file对象。你知道吗</p>
<p>其次,如果您的目标是计算字符串的匹配数,则不需要正则表达式。您可以使用字符串函数<code>count()</code>。即使如此,将正则表达式调用放在引号中也是没有意义的。你知道吗</p>
<pre><code>match1 = "re.findall(pattern, file1.read())"
</code></pre>
<p>将字符串<code>"re.findall(pattern, file1.read())"</code>赋给变量<code>match1</code>。你知道吗</p>
<p>以下是一个适合您的版本:</p>
<pre><code>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)
</code></pre>