python-如何从文本文件的每一行提取字符串? [英] python - How to extract strings from each line in text file?

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

问题描述

我有一个文本文件,用于检测活动监视器的数量. 我想从每一行中提取特定数据并将其包含在列表中.

I have a text file that detects the amount of monitors that are active. I want to extract specific data from each line and include it in a list.

文本文件如下所示:

[EnumerateDevices]: Enumerating Devices.
DISPLAY\LGD03D7\4&ACE0355&1&UID68092928                     : Generic PnP Monitor
DISPLAY\ABCF206\4&ACE0355&1&UID51249920                     : Generic PnP Monitor
//
//   here can be more monitors...
//
2 matching device(s) found.

我需要在文本中间的UID之后获取数字:68092929,51249920 ..

I need to get the number after the UID in the middle of the text : 68092929 , 51249920 ..

我想到了下一个:

a.在文本中输入每一行

a. enter each line in text

b.看看是否存在"UID"字符串

b. see if "UID" string exist

c.如果存在,请执行以下操作:split(在这里我知道如何执行此操作.通过(")或(&")进行拆分

c. if it exists : split (here I dot know how to do it.. split by (" ") or ("&")

您有什么好建议可以建议吗?我不明白如何在UID之后获取数字(例如,如果下一个数字比上一个数字长) 如何获得执行以下命令的命令:(如果看到UID字符串,请获取所有数据,直到看到第一个空白为止")

Is there any good idea you can advise? I don't understand how can I get the numbers after the UID (if the next number is longer than the previous ones for example) how can I get a command that does : ("If you see UID string, get all the data until you see first blank")

有什么主意吗? 谢谢

推荐答案

使用正则表达式:

import re
p =re.compile(r'.*UID(\d+)')
with open('infile') as infile:
    for line in infile:
        m = p.match(line)
        if m:
           print m.groups[0]

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

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