簡體   English   中英

從文件中刪除多余的字符串

[英]remove extra strings from file

有沒有辦法從結果中刪除日期和心率:並將它們保存在文件中

2022.12.08 14:49:55 心率:-1 2022.12.08 14:49:55 靜息激越得分:-1 2022.12.08 14:49:56 心率:-1 2022.12.08 14:49:56 靜息激越得分: -1 2022.12.08 14:49:57 心率:-1 2022.12.08 14:49:57 靜息激越分數:-1 2022.12.08 14:49:58 心率:32 2022.12.08 14:49:58 靜息激越分數:-1 2022.12.08 14:49:59 心率:31 2022.12.08 14:49:59 靜息激越分數:-1 2022.12.08 14:50:00 心率:32 2022.12.08 14:50:00 靜息激越分數:-1 2022.12.08 14:50:01 心率:-1 2022.12.08 14:50:01 靜息激動得分:-1 2022.12.08 14:50:02 心率:-1 2022.12.08 14:50:02 靜息激動分數:-1 2022.12.08 14:50:03 心率:-1 2022.12.08 14:50:03 靜息激動分數:-1

我想要 output 作為

-1

-1

-1

-1

-1

假設您的輸入是在一個文本文件中,您可以將整個文件作為字符串讀入一個變量並執行如下操作:

 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

如果你有一個輸入文件並且想要一個 output 文件,它可能看起來像這樣:

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')

您可能需要考慮使用正則表達式來獲取分數

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM