Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中组合两个打印函数?_Python_Python 3.x - Fatal编程技术网

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

如何在python中组合两个打印函数?,python,python-3.x,Python,Python 3.x,我想打印针对同一文件运行的两个正则表达式的输出 我试过了 import re with open("C:\\Users\\frank\Documents\\file-with-digits.txt") as myfile: print(re.findall(r'organizationID as int\s*=\s*(\d+)', myfile.read())) print(re.findall(r'organizationID\s*=\s*(\d+)', m

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

我试过了

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

在每种情况下,第二个print语句都不显示输出


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

这应该可以回答您的问题:

在您的具体情况下,您要做的是:

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

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

这应该可以回答您的问题:

在您的具体情况下,您要做的是:

import re
with open("C:\\Users\\frank\Documents\\file-with-digits.txt") as myfile:
    file_contents = myfile.read()
    print(re.findall(r'organizationID as int\s*=\s*(\d+)', file_contents ))
    print(re.findall(r'organizationID\s*=\s*(\d+)', file_contents ))
此外,根据经验:像读取文件这样的I/O操作通常很慢。因此,即使对一个文件调用两次
read()
达到了您预期的效果,也最好只调用一次,并将结果存储在一个变量中,这样您就可以重复使用它。

调用
file.read()
会耗尽文件内容,因此第二个模式将无法匹配。如果要重复使用文件内容,请将其分配给一个变量,然后可以根据需要多次引用该变量。调用
file.read()
会耗尽文件内容,因此第二个模式将无法匹配。如果要重复使用文件内容,请将其分配给变量,然后可以根据需要多次引用该变量。