次のような複数の行を含む複数の .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
:
s の前の数値を読み取り、配列に格納する方法を知りたいです。
>>> 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]
私は正規表現を使用しますが、これは@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]
または、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
あなたが話しているファイルの配列はどこですか