【发布时间】:2017-10-21 06:53:38
【问题描述】:
我的代码是:
quiz = {}
quiz["questions"]={}
templist = []
def checkint(i):
try:
int(i)
return True
except ValueError:
return False
with open("sample",'r') as f:
for x in f:
x.rstrip()
num,text = x.split(" ",1)
print(text)
num = num[:-1]
if checkint(num):
quiz["questions"][num] = {}
quiz["questions"][num]["question"] = text
templist.append(num)
else:
qn = templist.pop()
quiz["questions"][qn][num] = text
templist.append(qn)
示例文件为:
1. Who is the sower in the parable of wheat and tares?
a. Jesus
b. Peter
c. Angels
d. Satan
当我打印字典测验时,输出在每个值的末尾都包含换行符 \n。
{'问题': {'1': {'a': '耶稣\n', 'b': '彼得\n', 'c': 'Angels\n', 'd': 'Satan\n', 'question': '谁是播种者 小麦和稗子的比喻?\n'}, '2': {'question': '\n'}}}
为什么会这样?我应该怎么做才能摆脱\n?
【问题讨论】:
-
这与字典无关——如果您根本没有将它们写入字典,则从文件中读取的行仍然会有尾随换行符。请在未来尝试生成一个minimal reproducible example,其中删除了重新创建问题所必需的元素。
-
x = x.strip()
标签: python dictionary