【问题标题】:splitting the multiline string into a format in python? [closed]将多行字符串拆分为python中的格式? [关闭]
【发布时间】:2021-04-29 14:27:26
【问题描述】:

我正在尝试将多行字符串拆分为一种格式

我尝试了此链接https://www.w3schools.com/python/ref_string_split.asp 中的解决方案,但没有奏效

【问题讨论】:

    标签: python python-3.x string split


    【解决方案1】:
    lines = [line for line in txt.splitlines() if line]
    
    for idx in range(0, len(lines), 2):
      keys = lines[idx].split() 
      values = lines[idx+1].split()
      for k, v in zip(keys, values):
        print(f"{k}:{v}")
    

    输出:

    1.name:chandu
    2.address:madhuranagr
    3.option:234
    4a.option1:345
    4b.option2:456
    4c.option3:789
    

    【讨论】:

      【解决方案2】:

      这是一个可能的解决方案:

      # Gets an array where each entry is a line.
      lines = txt.split('\n')
      # Discard first and last lines, which are empty.
      lines = lines[1:-1]
      
      # Iterate over pairs of lines.
      for i in range(len(lines)//2):
        # Compute indices for the relevant lines
        question_index = 2*i
        answer_index = 2*i + 1
      
        # Split the entries in a line, using strip() to remove the last (empty) entry.
        question_parts = lines[question_index].strip().split(' ')
        answer_parts = lines[answer_index].strip().split(' ')
      
        # Print question-answer pairs.
        for j in range(len(question_parts)):
          # Skip questions without answers.
          if j < len(answer_parts):
            print('%s:%s' % (question_parts[j], answer_parts[j]))
      

      它解决了那个特定的例子,但它不能处理所有的边缘情况:例如,是否有可能缺少中间答案之一?如果是,那么这种情况下的数据结构如何?

      【讨论】:

      • 我认为您需要更好地指定输入格式。例如,如果您只有“456”而不是“345 456 789”行,会发生什么?我怎么知道答案指的是什么问题?它是否会回答 4a.option1、4b.option2、4c.option3 或 4d.option4 是模棱两可的,即使您在前后包含空格,例如“456”。
      猜你喜欢
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2021-11-20
      • 2016-12-31
      • 2019-02-16
      相关资源
      最近更新 更多