簡體   English   中英

有沒有辦法在文本文件中多次拆分一行?

[英]Is there a way to split a line more than once in a text file?

我有這個名為log.txt的文本文件。

1.a  Receiver Type            : REC-1
     Satellite System         : GPS
     Serial Number            : A123

1.b  Receiver Type            : REC-2
     Satellite System         : GPS
     Serial Number            : B456

1.c  Receiver Type            : REC-3
     Satellite System         : GPS
     Serial Number            : C789

我能夠在冒號':'之后打印'衛星系統'和'序列號'后的值。 但由於“接收器類型”行前面的3個字符,我不能對“接收器類型”執行相同的操作。 我能做到這一點嗎? 有沒有辦法多次拆分一條線? 完全是Python新手。 因此,任何有助於我推動球滾動的內容都將受到高度贊賞。 謝謝。

這是我目前擁有的代碼,只顯示冒號后的“衛星系統”和“序列號”的值。

with open('log.txt', 'r') as Log:
    for line in Log:
        if line.split(':')[0].strip() == 'Satellite System':
            sat_sys = line.split(':')[1].strip()
            print sat_sys

        if line.split(':')[0].strip() == 'Serial Number':
            ser_num = line.split(':')[1].strip()
            print ser_num

是.strip()混淆了東西,而不是.split(“:”),但你可以這樣做:

with open('log.txt', 'r') as Log:
    for line in Log:
        header = line.split(':')[0]
        if 'Satellite System' in header:
            sat_sys = line.split(':')[1].strip()
            print sat_sys
        elif 'Serial Number' in header:
            ser_num = line.split(':')[1].strip()
            print ser_num
        elif 'Receiver Type' in header:
            rec_typ = line.split(':')[1].strip()
            print rec_typ

暫無
暫無

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

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