擅长:python、mysql、java
<p>有几个错误,让我们逐一检查:</p>
<ol>
<li>引号中的任何东西都是字符串。把<code>"re.findall(pattern, file1.read())"</code>放在引号里就是一个字符串。如果你真的想打电话给关于芬德尔函数,不需要引号:)</li>
<li>检查<code>match1</code>是否为None,这非常好,但是应该返回匹配的,而不是初始模式。你知道吗</li>
<li>if语句不应缩进。你知道吗</li>
</ol>
<p>此外:</p>
<ul>
<li>打开文件后总是关闭它!因为大多数人都忘记了这一点,所以最好使用<code>with open(filename, action)</code><a href="https://stackoverflow.com/a/31334226/9222529">syntax</a>。你知道吗</li>
</ul>
<p>所以,综合起来,它看起来是这样的(为了清晰起见,我更改了一些变量名):</p>
<pre><code>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
</code></pre>