使用Python在文件中查找字符串并在同一行中提取整数值
作者:互联网
我是python的新手,有以下问题.
我有一个文本文件(filename.dat),它提供有关我的模型的信息.相关部分的摘要如下:
NUMBER OF ELEMENTS IS 1367466
NUMBER OF NODES IS 252624
NUMBER OF NODES DEFINED BY THE USER 248291
NUMBER OF INTERNAL NODES GENERATED BY THE PROGRAM 4333
TOTAL NUMBER OF VARIABLES IN THE MODEL 783873
我可以使用以下python命令搜索该行:
with open('filename.dat', 'r') as inF:
for line in inF:
if 'NUMBER OF ELEMENTS IS' in line:
print "true"
但是我不确定如何在’NUMBER OF ELEMENTS IS’的同一行中提取整数值(1367466).现在有人如何从与字符串字符混合的行中提取字符串数字?
解决方法:
用右边的空格分割线条,一次:
In [18]: line.rsplit(None, 1)
Out[18]: ['TOTAL NUMBER OF VARIABLES IN THE MODEL', '783873']
采取第二部分:
In [19]: line.rsplit(None, 1)[1]
Out[19]: '783873'
将其转换为int:
In [20]: int(line.rsplit(None, 1)[1])
Out[20]: 783873
您可以使用元组解包来使代码更清晰(如果您的整个文件是这种格式):
with open('filename.dat', 'r') as inF:
for line in inF:
label, number = line.rsplit(None, 1)
if 'NUMBER OF ELEMENTS IS' in label:
print "true"
number = int(number)
...
如果某些行具有不同的格式,则必须先搜索并稍后拆分:
with open('filename.dat', 'r') as inF:
for line in inF:
if 'NUMBER OF ELEMENTS IS' in line:
print "true"
label, number = line.rsplit(None, 1) # label is unused then
number = int(number)
...
标签:python-2-6,python 来源: https://codeday.me/bug/20190901/1780405.html