我试图做一个函数,在给定用户输入的情况下,可以将输入映射到文本文件中的字符串列表,并返回与文件中字符串对应的某个整数。基本上,我检查用户输入是在文件中,并返回文件中匹配字符串的索引。我有一个工作功能,但它看起来很慢并且容易出错。将用户输入映射到文本文件列表
def parseInput(input):
Gates = []
try:
textfile = open("words.txt")
while nextLine:
nextLine = textfile.readline()
Gates[n] = nextLine #increment n somewhere
finally:
textfile.close()
while n <= len(Gates):
nextString = Gates[n]
if input in nextString:
#Exit loop
with open("wordsToInts.txt") as textfile:
#Same procedure as the try loop(why isn't that one a with loop?)
if(correct):
return number
这似乎相当......不好。我似乎无法想到更好的方式来做到这一点。我完全控制words.txt和wordsToInts.txt(我应该结合这些吗?),所以我可以根据自己的喜好来格式化它们。我正在寻找建议重新:功能本身,但如果文本文件的更改会有所帮助,我想知道。我的目标是减少错误原因,但我会稍后添加错误检查。请提出一个更好的方法来编写这个函数。如果用代码编写,请使用Python。然而,伪码很好。