2016-07-19 44 views
0

我试图做一个函数,在给定用户输入的情况下,可以将输入映射到文本文件中的字符串列表,并返回与文件中字符串对应的某个整数。基本上,我检查用户输入是在文件中,并返回文件中匹配字符串的索引。我有一个工作功能,但它看起来很慢并且容易出错。将用户输入映射到文本文件列表

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。然而,伪码很好。

回答

0

我会说要合并文件。你可以有你的话,它们的对应值如下:

words.txt

string1|something here 
string2|something here 

然后你可以每行存储为一个条目字典和召回根据您输入的值:

def parse_input(input): 
    word_dict = {} 
    with open('words.txt') as f: 
     for line in f.readlines(): 
      line_key, line_value = line.split('|', 1) 
      word_dict[line_key] = line_value.rstrip('\n') 
    try: 
     return word_dict[input] 
    except KeyError: 
     return None 
0

我试图做的是,给定的来自用户的输入,可以映射输入到一个文本文件中的字符串列表,并返回一些整数对应于100的功能依赖于文件中的字符串。从本质上讲,我检查用户输入的是文件在什么和文件中返回匹配的字符串的索引

def get_line_number(input): 
    """Finds the number of the first line in which `input` occurs. 

    If input isn't found, returns -1. 
    """ 
    with open('words.txt') as f: 
     for i, line in enumerate(f): 
      if input in line: 
       return i 
    return -1 

此功能将满足你的描述规范与附加假设字符串你关心是分开的。值得注意的东西:

  1. Python中的文件对象充当其内容行上的迭代器。如果您只需检查每个单独的行,则无需将行读入列表中。

  2. enumerate函数采用一个迭代并返回发电机这产生像(index, element),其中element是在你的迭代和索引的元素是其迭代器内侧的位置的元组。

    • 术语迭代器意味着任何对象都是可以在for循环中访问的一系列事物。
    • 术语生成器意味着生成元素以通过“即时”迭代的对象。在这种情况下,这意味着您可以逐一访问文件的每一行,而无需将整个文件加载到机器的内存中。
  3. 该函数是用标准的Pythonic风格编写的,带有文档字符串,适当的变量名称和描述性名称。