【发布时间】:2016-07-19 23:06:42
【问题描述】:
我正在尝试创建一个函数,根据用户的输入,可以将输入映射到文本文件中的字符串列表,并返回与文件中的字符串对应的一些整数。本质上,我检查用户输入是否在文件中,并返回文件中匹配字符串的索引。我有一个工作功能,但它似乎很慢且容易出错。
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。但是,伪代码很好。
【问题讨论】:
标签: python function pseudocode