【问题标题】:Creating sets of specific extracted values from a .txt file (Python)从 .txt 文件创建特定提取值集 (Python)
【发布时间】:2022-11-15 17:18:18
【问题描述】:

我有一个 .txt 文件,其中用大写字母表示“NAMES”、“POINTS”和“SUMMARY”,每个文件后面都有包含数据的行。这三个组中的每一个都由一个空行分隔:

NAMES
John Cena
Sam Smith
Selena Gomez

POINTS
sixteen
forty
thirty

SUMMARY
eighth place
sixth place
first place

我的目标是创建三组独立的名称、要点和摘要。

我已经使用以下代码创建了一组名称(它按预期输出一组所有名称):

names = set()

for line in open('handout_example.txt'):
    line = line.strip()
    if not line:
        break
    names.add(line)

names.remove('NAMES')
print(names) #this outputs a set of all names

但是,我不确定如何创建一组点和一组摘要,因为它们位于空行之后而不是与名称不同的代码开头。 任何帮助将不胜感激!!提前谢谢你 <3

【问题讨论】:

    标签: python file set


    【解决方案1】:

    这是我的解决方案:

    names = set()
    points = set()
    summary = set()
    
    next = 0
    
    for line in open('handout_example.txt'):
        line = line.strip()
        if not line:
            next += 1
            continue
        if next == 0:
           names.add(line)
        elif next == 1:
           points.add(line)
        elif next == 2:
           summary.add(line)
    
    names.remove('NAMES')
    points.remove('POINTS')
    summary.remove('SUMMARY')
    
    print(f'{names}	{points}	{summary}')
    

    它很简单,可以做得更好,但我想这对你有用。

    编辑:更“漂亮”的版本:

    nps = dict({'names': set(), 'points': set(), 'summary': set()})
    nps_n = ['names', 'points', 'summary']
    
    next = 0
    
    for line in open('handout_example.txt'):
       line = line.strip()
    
       if not line:
          next += 1
          continue
       
       nps[nps[next]].append(line)
    

    【讨论】: