【问题标题】:Concatenate records from a file in Python在 Python 中连接文件中的记录
【发布时间】:2021-03-10 13:22:50
【问题描述】:

由于我是 Python 编程的新手,我需要在这里问一下 :-) 我有一个包含这样记录的文本文件

UCB: Some information
   FCB: More information
   FCB: More information
   FCB: More information
      WCB: Final information
   FCB: More information
   FCB: More information
      WCB: Final information
      WCB: Final information
      WCB: Final information
UCB: Some information
   FCB: More information
   FCB: More information
      WCB: Final information
   FCB: More information

FCB 和 WCB 记录的数量有时会有所不同。我唯一知道的是

  1. UCB 记录后面总是至少有一个 FCB 记录。
  2. FCB 记录属于最后读取的 UCB 记录
  3. WCB 记录属于最后读取的 FCB 记录
  4. FCB 记录可以有 0 到 100 条 WCB 记录
  5. UCB 记录数未知

我需要读取文件并将 UCB 记录与 FCB 记录连接当且仅当FCB 后跟一个(或多个)WCB 记录。在这种情况下,对于找到的每个 WCB,输出记录应该是 UCB + FCB + WCB。

任何建议如何在 Python 中执行此操作?

问候 霍贝

【问题讨论】:

    标签: python concatenation record


    【解决方案1】:

    您可以将最新的 UCB 和 FCB 父代存储在变量中,并附加到每个 WCB 的列表中。

    def myFunc(filepath):
        rv = []
    
        latest_ucb = None
        latest_fcb = None
    
        with open(filepath, 'r') as file:
            for line in file:
                line = line.lstrip() # remove leading whitespaces
                current_info = line[5:]
    
                if line[:3] == 'UCB':
                    latest_ucb = current_info
                elif line[:3] == 'FCB':
                    latest_fcb = current_info
                elif line[:3] == 'WCB':
                    rv.append(latest_ucb + latest_fcb + current_info)
    
        return rv
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2019-10-03
    • 2018-10-31
    • 2016-02-17
    • 2019-01-31
    • 2018-01-31
    • 1970-01-01
    相关资源
    最近更新 更多