【问题标题】:Build a dictionary from a list with a structured pattern从具有结构化模式的列表构建字典
【发布时间】:2019-05-29 04:17:23
【问题描述】:

如何从该文本文件中获取如下字典:

[Fri Aug 20]
shamooshak 4-0 milan
Tehran 2-0 Ams
Liverpool 0-2 Mes
[Fri Aug 19]
Esteghlal 1-0 perspolise
Paris 2-0 perspolise
[Fri Aug 20]
RahAhan 0-0 milan
[Wed Agu 11]
Munich 3-3 ABC
[Wed Agu 12]
RM 0-0 Tarakto
[Sat Jau 01]
Bayern 2-0 Manchester

我已经尝试了列表理解,用于带有枚举函数的循环。但我无法建立这个列表。

我想要的字典是: {'[Fri Aug 20]':[shamooshak 4-0 milan, Tehran 2-0 Ams,Liverpool 0-2 Mes],'[Fri Aug 19]':[Esteghlal 1-0 perspolise,Paris 2-0 perspolise]...等等。

【问题讨论】:

  • 请编辑您的问题,使其包含有效的 Python 数据结构

标签: python list dictionary converters


【解决方案1】:

假设您的数据是文本行...

def process_arbitrary_text(text):
    obj = {}
    arr = []
    k = None
    for line in text:
        if line[0] == '[' and line[-1] == ']':
            if k and arr: # omit empty keys?
                obj[k] = arr
            k = line
            arr = []
        else:
            arr.append(line)
    return obj

desired_dict = process_arbitrary_text(text)

编辑:既然你编辑说它是一个文本文件,只需包含以下模式

with open('filename.txt', 'r') as file:
    for line in file:
        # do something...or:
    text = file.readlines()

【讨论】:

    【解决方案2】:

    for 可以成为这里的救星

    a='''[Fri Aug 20]
    shamooshak 4-0 milan
    Tehran 2-0 Ams
    Liverpool 0-2 Mes
    [Fri Aug 19]
    Esteghlal 1-0 perspolise
    Paris 2-0 perspolise
    [Fri Aug 20]
    RahAhan 0-0 milan
    [Wed Agu 11]
    Munich 3-3 ABC
    [Wed Agu 12]
    RM 0-0 Tarakto
    [Sat Jau 01]
    Bayern 2-0 Manchester'''
    d={}
    temp_value=[]
    temp_key=''
    for i in a.split('\n'):
    
        if i.startswith('['):
            if temp_key and temp_key in d:
                d[temp_key]=d[temp_key]+temp_value
            elif temp_key:
                d[temp_key]=temp_value
    
            temp_key=i
            temp_value=[]
    
        else:
            temp_value.append(i)
    
    print(d)
    

    输出

    {'[Fri Aug 20]': ['shamooshak 4-0 milan', 'Tehran 2-0 Ams', 'Liverpool 0-2 Mes', 'RahAhan 0-0 milan'], '[Fri Aug 19]': ['Esteghlal 1-0 perspolise', 'Paris 2-0 perspolise'], '[Wed Agu 12]': ['RM 0-0 Tarakto'], '[Wed Agu 11]': ['Munich 3-3 ABC']}
    

    【讨论】:

      【解决方案3】:

      使用正则表达式(re 模块)和您的示例文本:

      text = '''[Fri Aug 20]
      shamooshak 4-0 milan
      Tehran 2-0 Ams
      Liverpool 0-2 Mes
      [Fri Aug 19]
      Esteghlal 1-0 perspolise
      Paris 2-0 perspolise
      [Fri Aug 20]
      RahAhan 0-0 milan
      [Wed Agu 11]
      Munich 3-3 ABC
      [Wed Agu 12]
      RM 0-0 Tarakto
      [Sat Jau 01]
      Bayern 2-0 Manchester'''
      x = re.findall('\[.+?\][^\[]*',text)
      x = [i.split('\n') for i in x]
      d = dict()
      for i in x:
          d[i[0]] = [j for j in i[1:] if j!='']
      

      它给出了以下字典d

      `{'[Fri Aug 20]': ['RahAhan 0-0 milan'], '[Sat Jau 01]': ['Bayern 2-0 Manchester'], '[Fri Aug 19]': ['Esteghlal 1-0 perspolise', 'Paris 2-0 perspolise'], '[Wed Agu 12]': ['RM 0-0 Tarakto'], '[Wed Agu 11]': ['Munich 3-3 ABC']}`
      

      我忽略了日期可能会重复,正如 mad_ 所指出的那样,以避免丢失数据将 for 循环替换为

      for i in x:
          d[i[0]] = []
      for i in x:
          d[i[0]] = d[i[0]]+[j for j in i[1:] if j!='']
      

      【讨论】:

      • 您确实意识到键 [Fri Aug 20] 的数据不匹配,因为您正在使用新值而不是追加来更新键
      猜你喜欢
      • 2021-11-10
      • 2013-10-21
      • 2018-08-10
      • 2015-09-25
      • 2022-12-14
      • 2016-01-16
      • 2012-12-24
      • 1970-01-01
      相关资源
      最近更新 更多