我试图将字符所说的行添加到一个空列表中并打印出来..但每次我运行代码时,它都会打印回一个空列表“[]”..但它应该打印出列表中字符所说的行
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)
我假设在文件数据中的角色和
:
之间可能有一些尾随空格。如果您能提供一些来自sketch.txt
的样本行,我们可以肯定地知道。无论如何,如果是这种情况,您也可以在role
值中调用.strip()
:实现这一点的另一种方法是使用字典捕获解析的数据,即不需要每个角色都使用
if
语句:相关问题 更多 >
编程相关推荐