【问题标题】:Read lines and make a dictionary [closed]阅读台词并制作字典[关闭]
【发布时间】:2021-09-16 07:57:10
【问题描述】:

由多行组成的原始txt文件格式如下:

Q1:
Number of responses: 100
Answers:
A. Python
B. Java
C. JavaScript

Q2:
...

我做了什么:

import re
file = 'file.txt'

text = open(file, "r", encoding='utf-8-sig').read()
textList = [i for i in textList if i != ""]
length = len(textList)
flag = length * [0]

pattern = re.compile(r'Q\d+')
for i in range(length):
    matches = pattern.findall(textList[i])
    if len(matches) > 0:
        if matches[0] == textList[i]:
            flag[i] = 1
    if textList[i] == 'Answers:':
        flag[i] = 2

我想知道我应该怎么把它变成这样的json格式:

{
    'Q1': {
         'Number of responses': 100,
         'Answer' : ['A. Python','B. Java','C. JavaScript']
    }
    'Q2': {
         ...
    }
}

【问题讨论】:

    标签: python readlines


    【解决方案1】:

    你可以试试regex

    # Assume the file content as follows
    
    # Question1: What do you do for fun?
    # Number of responses: 100
    # Answers:
    # A. Watching movies
    # B. Doing sports
    # C. Chat with friends
    
    # Question2: What do you do for fun?
    # Number of responses: 100
    # Answers:
    # A. Watching movies
    # B. Doing sports
    # C. Chat with friends
    
    import re
    data = open('file.txt').read()
    
    output = {}
    
    for i in re.findall(r'^(Question\d+).*\n.*\nAnswers:\n((?:^\w[\w. ]+\n)+)', data, re.MULTILINE):
        output[i[0]] = i[1].strip().split('\n')
        
    print(output)
    
    {'Question1': ['A. Watching movies', 'B. Doing sports', 'C. Chat with friends'], 'Question2': ['A. Watching movies', 'B. Doing sports']}
    

    【讨论】:

      【解决方案2】:

      假设您的个人答案总是由两个换行符分隔,您可以

      # make a dictionary
      answers = dict()
      
      # split at double newlines to get individual questions
      for q in data.split('\n\n'):
          # split each question into lines,
          # take the 1st line, 2nd line, 3rd line, and all the rest
          q, responses, _, *ans = q.splitlines()
      
          # and add it to the dict
          answers[q] = ans
      

      结果:

      {'Question1: What do you do for fun?': ['A. Watching movies',
        'B. Doing sports',
        'C. Chat with friends'],
       'Question2: Why?': ['A. Foo', 'B. Bar', 'C. Foobar']}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-25
        • 1970-01-01
        • 1970-01-01
        • 2014-03-18
        • 2014-04-04
        • 1970-01-01
        相关资源
        最近更新 更多