如何使用python从文本文件中的行读取特定字符?

时间:2012-06-10 13:09:29

标签: python text io character

我有多个.txt文件,其中包含多行类似于:

[class1] 1:-28 9:-315 13:-354227 2:-36.247 17:-342 8:-34 14:-3825
[class2] 14:-31.8679 7:-32.3582 2:-32.4127 1:-32.7257 8:-32.9804 16:-33.2156

我想知道如何在:之前读取数字并将它们存储在数组中。

3 个答案:

答案 0 :(得分:2)

>>> import re
>>> text = "[class1] 1:-28 9:-315 13:-354227 2:-36.247 17:-342 8:-34 14:-3825"
>>> map(int, re.findall(r'(\S+):\S+', text)) # You could also do map(float,...)
[1, 9, 13, 2, 17, 8, 14]

答案 1 :(得分:1)

或者不使用RE,如果你确定文件的语法保持不变,你可以使用它:

>>> arr
['[class1] 1:-28 9:-315 13:-354227 2:-36.247 17:-342 8:-34 14:-3825', '[class2] 14:-31.8679 7:-32.3582 2:-32.4127 1:-32.7257 8:-32.9804 16:-33.2156']
>>> newArr = [map(lambda y: int(y[:y.index(":")]),x.split(" ")[1:]) for x in arr]
>>> newArr
[[1, 9, 13, 2, 17, 8, 14], [14, 7, 2, 1, 8, 16]]

<强>更新

如果您有多个文件,可能会做这样的事情(基于@jamylak更清晰的解决方案版本):

[[[int(x.split(':')[0]) for x in line.split()[1:]] for line in open(fileName)] for fileName in fileNames]

其中fileNames是您正在谈论的文件数组

答案 2 :(得分:1)

我会使用正则表达式,但这里的版本没有,比@Thrustmaster的解决方案imo更清晰。

>>> text = "[class1] 1:-28 9:-315 13:-354227 2:-36.247 17:-342 8:-34 14:-3825"
>>> [int(x.split(':')[0]) for x in text.split()[1:]]
[1, 9, 13, 2, 17, 8, 14]