如何在python中的2条特定行之间读取 [英] How to read between 2 specific lines in python

查看:567
本文介绍了如何在python中的2条特定行之间读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,其内容与此相似.

I'm having a variable which holds the contents that is somewhat similar to this

**** SOME JUNK DATA ****
**** SOME JUNK DATA ****
**** SOME JUNK DATA ****
Main_data1;a;b;c;dss;e;1
Main_data2;aa;bb;sdc;d;e;2
Main_data3;aaa;bbb;ccce;d;e;3
Main_data4;aaaa;bbbb;cc;d;e;4
Main_data5;aaaaa;bbbbb;cccc;d;e;5
**** SOME JUNK DATA ****
**** SOME JUNK DATA ****
**** SOME JUNK DATA ****

我想读取以Main_data1开头的数据.{仅读取最后一列并将其存储到列表中}.请注意,这是一个保存此数据的变量,而不是文件.

I want to read data that starts with Main_data1.{ Read only the last column and store it into a list} . Please note that this is a variable that holds this data and this is not a file.

我想要的输出:

Some_list=[1,2,3,4,5]

我想使用这样的东西.

for line in var_a.splitlines():
     if Main_data1 in line:
        print (line)

但是我需要阅读200列以上的最后一列.这样做可能是一种有效的方法

But there are more than 200 lines from which I need to read the last column. What could be an efficient way of doing this

推荐答案

您可以使用列表推导来存储数字:

You can use a list comprehension to store the numbers :

my_list = [int(line.strip().split(';')[-1]) for line in my_var.split('\n') if line.startswith('Main_data5')]

还请注意,作为一种更具断言意义的方法,最好使用str.startswith()方法而不是in运算符. (关于这种可能在一行的中间出现Main_data5的一行!)

Also note that as a more pyhtonic way you better to use str.startswith() method rather than in operator. (with regards to this poing that it might happen to one line has Main_data5 in the middle of the line!)

如果有两种情况下的行开头,则可以使用具有两个startswith条件的or运算符.

If you have two case for start of the line you can use an or operator with two startswith consition.

my_list = [int(line.strip().split(';')[-1]) for line in my_var.split('\n') if line.startswith('Main_data5') or line.startswith('Main_data1')]

但是如果您有更多的关键字,则可以使用正则表达式.例如,如果要将所有统计数据的线性数与Main_data匹配,并在其后加上数字,则可以使用re.match():

But if you have more key-words you can use regex.For example if you want to match all the linse that stats with Main_data and followed by a number you can use re.match():

import re
my_list = [int(line.strip().split(';')[-1]) for line in my_var.split('\n') if re.match(r'Main_data\d.*',line)]

这篇关于如何在python中的2条特定行之间读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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