【问题标题】:Mapping User Input to Text File List将用户输入映射到文本文件列表
【发布时间】: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


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

      我正在尝试创建一个函数,根据用户的输入,它可以将输入映射到文本文件中的字符串列表,并返回与文件中的字符串相对应的整数。本质上,我检查用户输入是否在文件中,并返回文件中匹配字符串的索引

      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 风格编写,带有文档字符串、变量名称的适当大小写和描述性名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-28
        • 1970-01-01
        • 2019-08-26
        • 1970-01-01
        • 1970-01-01
        • 2012-02-11
        • 2022-01-03
        相关资源
        最近更新 更多