【问题标题】:Using the read function in a while loop在 while 循环中使用 read 函数
【发布时间】:2025-04-05 08:05:01
【问题描述】:

我不确定如何正确获取读取功能以执行我想要的操作。我希望它循环遍历文件中的字符列表,直到它到达字符“#”。我希望它查看每个字符,如果它是元音,则将其附加到列表中。我在其他帮助线程中看到的 read 函数的文档让我感到困惑。到目前为止,我有这个:

def opt():
    filename = input("Enter the name of your input file: ")
    infile = open(filename, 'r')
    a = []
    vowel = infile.read(1)
    while (vowel != '#'):
        if vowel == "A":
            a.append(vowel)
            vowel = infile.read(1)
        elif vowel == "E":
            a.append(vowel)
            vowel = infile.read(1)
        elif vowel == "I":
            a.append(vowel)
            vowel = infile.read(1)
        elif vowel == "O":
            a.append(vowel)
            vowel = infile.read(1)
        elif vowel == "U":
            a.append(vowel)
            vowel = infile.read(1)
        else:
            vowel = infile.read(1)
    return (a)

注意 else 运算符,如果它是辅音 - 它只会转到下一个字符。

我做错了什么?

谢谢

【问题讨论】:

  • .read() 没有参数读取整个文件 - 没有必要将其放入循环中,因为将没有任何内容可供读取。你想让.read(1) 得到一个字符。
  • 我以前有这个,但是当我将所有 .read() 切换到 .read(1) 时,我的列表只有元音 A。

标签: python-3.x function while-loop


【解决方案1】:

如果我是你,我会这样做

def opt():
    filename = input("Enter the name of your input file: ")
    infile = open(filename, 'r')
    a = []
    vowel = infile.read(1)
    while vowel != '#':
        if vowel in ('A', 'E', 'I', 'O', 'U'):
            a.append(vowel)
        vowel = infile.read(1)
    return a

【讨论】:

  • 你能显示你的文件内容和你的预期输出吗?
  • 我解决了这个问题。我在 OP 中的东西是正确的,我只是没有考虑小写(我很傻)..