我試圖做一個函數,在給定用戶輸入的情況下,可以將輸入映射到文本文件中的字符串列表,並返回與文件中字符串對應的某個整數。基本上,我檢查用戶輸入是在文件中,並返回文件中匹配字符串的索引。我有一個工作功能,但它看起來很慢並且容易出錯。將用戶輸入映射到文本文件列表
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。然而,僞碼很好。