使用readline方法和字典时出现键错误

2024-04-19 20:09:45 发布

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

我试图根据字典生成字符串的数值,但每当我试图运行程序时,都会收到一个错误。你知道吗

key error:'\n'

有什么问题吗?我想这可能是readline方法,我有两个,这样我就可以读每一个2行测试数据.txt你知道吗

key = {'A':1,
   'B':2,
   'C':3,
   'D':4,
   'E':5,
   'F':6,
   'G':7,
   'H':8,
   'I':8,
   'J':10,
   'K':11,
   'L':12,
   'M':13,
   'N':14,
   'O':15,
   'P':16,
   'Q':17,
   'R':18,
   'S':19,
   'T':20,
   'U':21,
   'V':22,
   'W':23,
   'X':24,
   'Y':25,
   'Z':26}

infile = open("testdata.txt","r")

apro = infile.readline()
bpro = infile.readline()

aproresult = 1
bproresult = 1

for i in apro:
    aproresult *= key[i]
print(aproresult)

outfile = open("testdataAnswer.txt","w")

infile.close()

下面是testdata文件:

COMETQ
HVNGAT

Tags: 方法key字符串程序txtreadline字典错误
1条回答
网友
1楼 · 发布于 2024-04-19 20:09:45

你的readline()函数可能在换行符中读取,这就是你得到\n的原因。您可能可以使用rstrip()这样的方法去除尾随空格。你知道吗

apro = infile.readline()
bpro = infile.readline()

# Get rid of the line break using rstrip here
apro = apro.rstrip() 
bpro = bpro.rstrip()

相关问题 更多 >