我试图将字符所说的行添加到一个空列表中并打印出来

2024-04-18 14:18:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将字符所说的行添加到一个空列表中并打印出来..但每次我运行代码时,它都会打印回一个空列表“[]”..但它应该打印出列表中字符所说的行

import os
os.getcwd()
os.chdir("C:\\Users\\Toshiba\\Desktop\\headfirstpython\\chapter3")


man = []
other = []
try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if role == 'man':
                man.append(line_spoken)
            elif role == 'other man':
                other.append(line_spoken)
        except ValueError:
            pass
    data.close()    
except IOError:
    print('the datafile is missing')

print(man)
print(other)

Tags: 代码列表dataosline字符roleeach
1条回答
网友
1楼 · 发布于 2024-04-18 14:18:10

我假设在文件数据中的角色和:之间可能有一些尾随空格。如果您能提供一些来自sketch.txt的样本行,我们可以肯定地知道。无论如何,如果是这种情况,您也可以在role值中调用.strip()

man = []
other = []
try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            role = role.strip()
            if role == 'man':
                man.append(line_spoken)
            elif role == 'other man':
                other.append(line_spoken)
        except ValueError:
            pass
    data.close()    
except IOError:
    print('the datafile is missing')

print(man)
print(other)

实现这一点的另一种方法是使用字典捕获解析的数据,即不需要每个角色都使用if语句:

parsed_lines = {}
try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            role = role.strip()
            parsed_lines[role] = parsed_lines.get(role, [])
            parsed_lines[role].append(line_spoken)            
        except ValueError:
            pass
    data.close()    
except IOError:
    print('the datafile is missing')

print(f'parsed_lines: {parsed_lines}')

相关问题 更多 >