简体   繁体   中英

remove extra strings from file

Is there any wany to remove the date and heartrate: from the result and them save them in file

2022.12.08 14:49:55 Heartrate: -1 2022.12.08 14:49:55 Resting Agitation Score: -1 2022.12.08 14:49:56 Heartrate: -1 2022.12.08 14:49:56 Resting Agitation Score: -1 2022.12.08 14:49:57 Heartrate: -1 2022.12.08 14:49:57 Resting Agitation Score: -1 2022.12.08 14:49:58 Heartrate: 32 2022.12.08 14:49:58 Resting Agitation Score: -1 2022.12.08 14:49:59 Heartrate: 31 2022.12.08 14:49:59 Resting Agitation Score: -1 2022.12.08 14:50:00 Heartrate: 32 2022.12.08 14:50:00 Resting Agitation Score: -1 2022.12.08 14:50:01 Heartrate: -1 2022.12.08 14:50:01 Resting Agitation Score: -1 2022.12.08 14:50:02 Heartrate: -1 2022.12.08 14:50:02 Resting Agitation Score: -1 2022.12.08 14:50:03 Heartrate: -1 2022.12.08 14:50:03 Resting Agitation Score: -1

I want output as

-1

-1

-1

-1

-1

Assuming your input is in a text file you could read the whole file as string into a variable and do something like this:

 input_string = """2022.12.08 14:49:55 Heartrate : -1 2022.12.08 14:49:55 Resting Agitation Score : -1
     2022.12.08 14:49:56 Heartrate : -1 2022.12.08 14:49:56 Resting Agitation Score : -1
     2022.12.08 14:49:57 Heartrate : -1 2022.12.08 14:49:57 Resting Agitation Score : -1
     2022.12.08 14:49:58 Heartrate : 32 2022.12.08 14:49:58 Resting Agitation Score : -1
     2022.12.08 14:49:59 Heartrate : 31 2022.12.08 14:49:59 Resting Agitation Score : -1
     2022.12.08 14:50:00 Heartrate : 32 2022.12.08 14:50:00 Resting Agitation Score : -1
     2022.12.08 14:50:01 Heartrate : -1 2022.12.08 14:50:01 Resting Agitation Score : -1
     2022.12.08 14:50:02 Heartrate : -1 2022.12.08 14:50:02 Resting Agitation Score : -1
     2022.12.08 14:50:03 Heartrate : -1 2022.12.08 14:50:03 Resting Agitation Score : -1"""

lines = input_string.split('\n')
for line in lines:
    print(line.split(':')[-1].strip()) # prints items after last ':' without whitespace

if you have an input file and want an output file it could look something like this:

with open("input.txt", "r", encoding="utf-8") as file:
lines = file.readlines()

with open("output.txt", "w", encoding="utf-8") as file:
    for line in lines:
        file.write(line.split(':')[-1].strip() + '\n')

You may want to consider a regular expression for getting the score

import re

sensor_input = '2022.12.08 14:49:55 Heartrate : -1 2022.12.08 14:49:55 Resting Agitation Score : -1'

# Find and extract score
match_ = re.search('Resting Agitation Score : (-?\d*)', sensor_input)

int(match_.group(1)) # returns -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM