0

我有一个(ASCII)文件,foo.txt里面有很多东西,但我只关心第 2 行的三个数字(由空格分隔)。供您参考(我不知道它是否相关)此行之前和之后的行数与第 2 行不同。

我想从第 2 行获取这三个数字并将它们存储为三个单独的整数(无论是三个单独的变量还是长度为 3 的列表,我都不在乎)。

我曾经linecache.getline()专门从文件中获取该行,但它将该行作为一个长字符串拉出(而不是让行上的每个数字都是它自己的字符串)并且我不知道如何从结果中提取三个数字细绳。

这是我的代码:

import linecache
linetemp = linecache.getline('foo.txt',2)
#nr = [int(i) for i in line.split(linetemp)]
print nr

注释行是我尝试将 linetemp 中的数字提取为整数,但由于 linetemp 是一个字符串(而不是字符串列表),它不起作用。

如果您可以改进我上面使用linecache.getline()的方法,或者如果您有另一种方法从第 2 行中提取三个数字,foo.txt我会很高兴。

4

2 回答 2

2

尝试

nr = [int(i) for i in linetemp.split()]

您需要在split()要拆分的字符串上调用该函数。

例子:

In [1]: linetemp = '  12     27   435'

In [2]: nr = [int(i) for i in linetemp.split()]

In [3]: nr
Out[3]: [12, 27, 435]
于 2014-08-27T19:31:35.627 回答
1

我不会linecache在这里使用 - 这是为了其他目的 - 而是使用 anislice来限制您正在阅读的文件的范围,然后将该行转换为ints:

from itertools import islice

with open('foo.txt') as fin:
    line2 = next(islice(fin, 1, None), '')
    nr = [int(word) for word in line2.split()]

如果您不想要导入,那么您可以执行以下操作:

with open('foo.txt') as fin:
    next(fin, '') # skip first line
                                # next line or blank
    nr = [int(word) for word in next(fin, '').split()]
于 2014-08-27T19:38:25.343 回答