2017-04-14 45 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] 
相關問題