2017-04-14 52 views

回答

0
with open("file.txt") as f: 
    lines=f.readlines() 
    for i in lines: 
     if i.__contains__("START"): 
      print i 

假设你有一个包含数据的file.txt的 你可以使用下面的代码 Happing编码

+1

为什么你使用'__contains__',而不是'in'? –

2

如从命令行一个衬里:

代码:

python -c "import sys;[sys.stdout.write(l) for l in sys.stdin if ' START ' in l]" < file1 

结果:

[739:246050] START of MACThread:receved msg type[47] 
[739:247059] START of MACThread:receved msg type[47] 
-2

使用条件表达式'START' in line其中line是要检查线路。

0

您可以使用re

查看演示。

https://regex101.com/r/sLKG1U/3

import re 

regex = r"^\[[^\]]*\]\s*(START\b.*)" 

test_str = ("[739:246050] START of MACThread:receved msg type[47]\n" 
"[739:247021] PHYThrad: DSPMsgQ Received: msg type is[130] and SFNSF [14997] [SFN:937 SF:5]\n" 
"[739:247059] START of MACThread:receved msg type[47]") 

matches = re.finditer(regex, test_str, re.MULTILINE) 

for matchNum, match in enumerate(matches): 
    matchNum = matchNum + 1 

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group())) 

    for groupNum in range(0, len(match.groups())): 
     groupNum = groupNum + 1 

     print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end =  match.end(groupNum), group = match.group(groupNum))) 
1

斯蒂芬·劳赫给出的答案是很酷,但我认为你是python的新手,所以这里是一个基本功能。

考虑,“START”必须始终在消息的开始,而不是之间像,

[739:247021] PHYThrad: START DSPMsgQ Received: msg type is[130] and SFNSF [14997] [SFN:937 SF:5] # START at second index after split. 

如果我们考虑以上使用的情况下,这里是可以打印本"START"线功能在日志消息开始的文件中。

def getStart(filename): 
    with open(filename, "r") as reader: 
     for lines in reader.readlines(): # get list of lines 
      start = lines.split(' ')[1] # Split with space, and check the word is "START" 
      if start =='START': 
       print lines 

getStart("a.txt") # considering your filename is a.txt. 

输出:

[739:246050] START of MACThread:receved msg type[47] 

[739:247059] START of MACThread:receved msg type[47] 
相关问题