如何使用python从文本文件中的行读取特定字符? [英] How to read specific characters from lines in a text file using python?

查看:1022
本文介绍了如何使用python从文本文件中的行读取特定字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have multiple .txt files that contain multiple lines similar to this:

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

这篇关于如何使用python从文本文件中的行读取特定字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆