-1
Here is my code

def ExtractTimeAndFrequency():

for line in ft.split('\r\n'):
    if 'cpu7' in line:
        tm = re.findall(r"([0-2][0-9]:[0-5][0-9]:[0-5][0-9])", line)
        fr= re.findall(r"\d{7}", line)
return fr, tm

file contents are here:

15:23:48 cpu0 1708800
15:23:48 cpu1 1708801
15:23:48 cpu2 1708802
15:23:48 cpu3 1708803
15:23:48 cpu4 1708804
15:23:49 cpu5 1708805
15:23:49 cpu6 2208006
15:23:49 cpu7 2208007
15:23:49 Temp 326

15:23:52 cpu0 1708808
15:23:52 cpu1 1708809
15:23:52 cpu2 1708810
15:23:52 cpu3 1708811
15:23:52 cpu4 1708812
15:23:52 cpu5 1708813
15:23:52 cpu6 2208014
15:23:52 cpu7 2208015
15:23:53 Temp 327

i should be getting only those matches that are for cpu7 but i am getting all the matches from cpu0 to cpu7

rockstar
  • 3
  • 3
  • Please paste the contents on the files directly instead of a screenshot. In addition, can you please format your code so it's easier to read? – Omri Bahat Treidel Apr 16 '20 at 01:05
  • ya i saw its not porperly formatted. fixing it – rockstar Apr 16 '20 at 01:14
  • i have formatted it now. i hope its readable. sorry i am new to SOF – rockstar Apr 16 '20 at 01:27
  • Double check the value of `line` (`print(f'Line is {line}')`), it looks like the split by `(\r\n)` is probably returning the entire file in 1 line. Try removing the `\r`. Or process the file line by line - check out this [Question and Answers](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – DaveStSomeWhere Apr 16 '20 at 01:35

1 Answers1

0

You might consider using with open for your file handling (you don't show what you are doing in your code). Then you can extend a list for each additional value of fr and tm. Using extend since each iteration only produces a list with a single value and you probably don't want to over write and just end up with the last value.

Is something like this what you are looking for (based on your test data)?

import re


def ExtractCpuAndFrequency():
    with open('../testData/so1.txt') as text_file:
        for line in text_file:
            if 'cpu7' in line:
                tm.extend(re.findall(r"([0-2][0-9]:[0-5][0-9]:[0-5][0-9])", line))
                fr.extend(re.findall(r"\d{7}", line))
    return fr, tm


tm = []
fr = []
result_fr, result_tm = ExtractCpuAndFrequency()

print(f'Result fr is {result_fr}')
print(f'Result tm is {result_tm}')

Results with the two values from the rows with "cpu7":

Result fr is ['2208007', '2208015']
Result tm is ['15:23:49', '15:23:52']
DaveStSomeWhere
  • 2,475
  • 2
  • 22
  • 19