将用户输入映射到文字文件列表

2024-10-03 21:27:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试创建一个函数,在给定用户输入的情况下,可以将输入映射到文本文件中的字符串列表,并返回与文件中的字符串相对应的整数。本质上,我检查用户输入的内容是否在文件中,并返回文件中匹配字符串的索引。我有一个工作功能,但它似乎很慢,容易出错。你知道吗

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。然而,伪代码是好的。你知道吗


Tags: 文件函数字符串txtloopinputifopen
2条回答

I'm trying to make a function that, given input from the User, can map input to a list of strings in a text file, and return some integer corresponding to the string in the file. Essentially, I check if what the user input is in the file and return the index of the matching string in the file

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是迭代器中的一个元素,index是它在迭代器中的位置。你知道吗

    • iterator一词是指任何对象,它是可以在for循环中访问的一系列内容。你知道吗
    • 术语生成器是指生成元素以“动态”遍历的对象。在这种情况下,这意味着您可以逐个访问文件的每一行,而无需将整个文件加载到计算机内存中。你知道吗
  3. 此函数以标准Pythonic样式编写,带有docstring、变量名的适当大小写和描述性名称。

我想把这些文件合并起来。您可以将单词及其对应的值设置为:

文字.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

相关问题 更多 >