【问题标题】:Read a specific line or character from a text file, not recognizing the text从文本文件中读取特定的行或字符,但无法识别文本
【发布时间】:2021-01-21 18:40:03
【问题描述】:

veriftype 有效,但 veriftype2 无效。是不是因为我读取第二行的方法不准确?它正在读取的文本文件的每一行都有一个字符,每行有一个 x 或一个 o。我尝试只使用 f.read(2) 但似乎没有一个人能做到这一点。我似乎找不到任何其他问题来源,因为当我打印应该是该行值的变量时,它给了我正确的值,但是 if 语句没有运行,它只是跳到其他部分。

def veriftype(self):
    f = open("Transfert.txt", "r")
    y = f.readline(1)
    print (y)
    if y == "x":
        if type(self) == Retriever or type(self) == Shepherd:
            self.points += 1
            print("It worked for the dogs.")
        else:
            print("It recognized the type wasn't correct, so it didn't get any points.")
    elif y == "o":
        print("It recognized the o")
    else:
        print("It didn't recognize anything")
    print(self.points)


def veriftype2(self):
    with open("Transfert.txt") as f:
        ligne = f.readlines()
    z = ligne[2]
    print(z)
    if ligne[2] == "x":
        if type(self) == Perroquet or type(self) == Macaw:
            self.points += 1
            print("It worked for the birds.")
        else:
            print("It recognized the type wasn't correct, so it didn't get any points.")
    elif ligne[2] == "o":
        print("It recognized the o")
    else:
        print("It didn't recognize anything")
    # print(self.points)

【问题讨论】:

  • 第一个函数获取第一行的第一个字符;第二个函数获取第三行的 whole (即从零开始索引)。调试文本值时应始终使用repr(),以便可以看到任何不可打印的字符。因此,print(repr(y)) 将为第一个函数输出 'x'print(repr(z)) 将为第二个函数输出 'x\n'。如果每行只有一个字符,您可以使用f.read().split() 将它们全部放在一个列表中。这将自动删除所有空格(包括空行)。

标签: python function text methods


【解决方案1】:

您的代码可以工作,但它无法识别字符,因为 readlines() 还包含换行符,因此它读取的是 'x\n' 而不是 'x'。因此没有文字匹配。将.readlines() 替换为.read().splitlines() 即可解决此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多