如何在python中组合两个打印函数?



我想打印针对同一文件运行的两个正则表达式的输出。

我试过了

import re
with open("C:\Users\frankDocuments\file-with-digits.txt") as myfile:
print(re.findall(r'organizationID as ints*=s*(d+)', myfile.read()))
print(re.findall(r'organizationIDs*=s*(d+)', myfile.read()))

import re
with open("C:\Users\frankDocuments\file-with-digits.txt") as myfile:
print(((re.findall(r'organizationID as ints*=s*(d+)', myfile.read())), re.findall(r'organizationIDs*=s*(d+)', myfile.read())))

在每种情况下,第二个print语句都没有输出。

如果我单独运行它们,它们都显示它们唯一的输出。如何将它们组合起来,以便看到两个正则表达式的输出?我当然可以打开文件两次并分别运行它们,但我认为必须有可能将它们组合在一起。

这应该可以回答您的问题:为什么我不能在打开的文件上调用两次read() ?

在你的特定情况下,你要做的是:

import re
with open("C:\Users\frankDocuments\file-with-digits.txt") as myfile:
file_contents = myfile.read()
print(re.findall(r'organizationID as ints*=s*(d+)', file_contents ))
print(re.findall(r'organizationIDs*=s*(d+)', file_contents ))

另外,根据经验:像读取文件这样的I/o操作通常很慢。因此,即使在一个文件上调用read()两次得到了预期的效果,也最好只调用一次,并将结果存储在一个变量中,以便您可以重用它。

最新更新