简体   繁体   English

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

[英]How to read specific characters from lines in a text file using python?

I have multiple .txt files that contain multiple lines similar to this: 我有多个.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

I want to know how to read the numbers before the : s and store them in an array. 我想知道如何在:之前读取数字并将其存储在数组中。

>>> 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]

Or without using RE, if you know for sure the syntax of the file remains the same, you could use this: 或者不使用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]]

UPDATE: 更新:

If you have several files, may be you would do something like this (based on @jamylak's clearer version of my solution): 如果您有多个文件,可能会执行以下操作(基于@jamylak解决方案的更清晰版本):

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

where fileNames is the array of files you are speaking about 其中fileNames是您正在谈论的文件数组

I would use regex but here is a version without, clearer than @Thrustmaster's solution imo. 我将使用正则表达式,但这是一个没有@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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM