我尝试创建一个函数,在给定用户输入的情况下,可以将输入映射到文本文件中的字符串列表,并返回与文件中的字符串相对应的整数。本质上,我检查用户输入的内容是否在文件中,并返回文件中匹配字符串的索引。我有一个工作功能,但它似乎很慢,容易出错。你知道吗
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
这似乎有点。。。糟糕。不过,我似乎想不出更好的办法。我完全控制了一切文字.txt以及wordsToInts.txt文件(我应该合并这些吗?),所以我可以随意格式化它们。我在寻找关于函数本身的建议,但是如果对文本文件的更改有帮助,我想知道。我的目标是减少错误的原因,但稍后我将添加错误检查。请建议一个更好的方法来写这个函数。如果用代码编写,请使用Python。然而,伪代码是好的。你知道吗
此函数将满足您描述中的规范,并假设您关心的字符串位于单独的行中。值得注意的是:
Python中的文件对象在其内容行上充当迭代器。如果您只需要检查每一行,就不必将行读入列表。
enumerate
函数接受一个迭代器并返回一个生成器,该生成器生成一个类似(index, element)
的元组,其中element
是迭代器中的一个元素,index是它在迭代器中的位置。你知道吗此函数以标准Pythonic样式编写,带有docstring、变量名的适当大小写和描述性名称。
我想把这些文件合并起来。您可以将单词及其对应的值设置为:
文字.txt
然后,您可以将每一行存储为字典的条目,并根据您的输入重新调用值:
相关问题 更多 >
编程相关推荐