Python 程序读取文本文件然后将行数、每行的单词和元音以及总单词和元音写入文本文件不起作用

问题描述 投票:0回答:2

对于 python 和一般编程来说是新手,我正在努力让这个程序正确运行。它必须:

  1. 读取一个文本文件,如果该文件不存在,则必须指示该人重新输入该文本文件。我有这部分工作。
  2. 计算行数、每行中的单词和每行中的元音并将这些数量输出到文本文件。
  3. 计算单词和元音的总数并在文本文件的底部输出。
  4. 我不能为此导入操作系统以外的任何东西。我不知道如何使用 list 函数,但我可能会在代码中使用它,本质上如果我没有使用过它并且它是一个更好的选择我可能还没有在课堂上学习它。

所以输入测试文件说:

"This is a

test file

to see if

the program works."

The output text file should say:

Line Number: 1

Number of vowels in line 1: 3

Number of words in line 1: 3

Line Number: 2

Number of vowels in line 2: 3

Number of words in line 2: 2

// etc. Then at the bottom:

Total number of vowels in the file: 14

Total number of words in the file: 11

相反,根据我尝试使用的循环语句,我得到无限行、两行或 8 行。单词和元音的计数已关闭。

根据我们在课堂上学到的知识,这是我目前所掌握的:

import os
fileName = input("What is the name of the .txt file you would like to open? ")
while os.path.exists(fileName) == False:
    print("Error, file not found.")
    fileName = input("What is the name of the .txt file you would like to open? ")
    if os.path.exists(fileName) == True:
        break
    else:
        print("error")
        continue

fileOut = open("answer.txt", 'w') #works to here

numLines = 0

totVowels = 0
totWords = 0

fileIn = open(fileName, 'r')
    
for line in fileIn:
    line = fileIn.readline()
    if line != "":
        numLines += 1
        numWords = len(line.split(" "))
        fileOut.write("Line number: %0d" % numLines)
        fileOut.write("\n")
        numA = line.count('A')
        numE = line.count('E')
        numI = line.count('I')
        numO = line.count('O')
        numU = line.count('U')
        numLa = line.count('a')
        numLe = line.count('e')
        numLi = line.count('i')
        numLo = line.count('o')
        numLu = line.count('u')
        numVowels = numA + numE + numI + numO + numU + numLa + numLe + numLi + numLo + numLu
        fileOut.write("Number of vowels in line %0d: %0d" %(numLines, numVowels))
        fileOut.write("\n")
        fileOut.write("Number of words in line %0d: %0d" %(numLines, numWords))
        fileOut.write("\n")
        fileOut.write("\n")
    else:
        for lines in fileIn.readlines():
            words2 = lines.split()
            totWords += len(words2)
            if 'a' in words2:
                totVowels += 1
            elif 'e' in words2:
                totVowels += 1
            elif 'i' in words2:
                totVowels += 1
            elif 'o' in words2:
                totVowels += 1
            elif 'u' in words2:
                totVowels += 1
            elif 'A' in words2:
                totVowels += 1
            elif 'E' in words2:
                totVowels += 1
            elif 'I' in words2:
                totVowels += 1
            elif 'O' in words2:
                totVowels += 1
            elif 'U' in words2:
                totVowels += 1
            else:
                fileOut.write("\n")
                fileOut.write("+++++++++++++++++")
                fileOut.write("\n")
                fileOut.write("Total number of vowels in file: %0d" % totVowels)
                fileOut.write("\n")
                fileOut.write("Total number of words in file: %0d" % totWords)
                
                        

print("answer.txt file has been created. See file for counts.")
fileIn.close()
fileOut.close()

老实说,此时我真的迷路了,我一直在疯狂地翻阅我的笔记,试图弄清楚我遗漏了什么,但我碰壁了,我的精神已经崩溃了。我觉得自己被扔进了深水区,但还没有学会游泳。任何帮助或建议表示赞赏。

python count text-files readline writefile
2个回答
0
投票

工作到此为止:

for line in fileIn:

这样做是遍历

fileIn
中的行。因此,在该循环中,
line
是一个带有一行文本的
str
。计算其中的单词和元音的数量,并将这些结果写入输出文件。然后将这些结果添加到总数中。循环将继续下一行。

因此,您不需要调用

readline()
readlines()

然后循环之后,将总计写入输出文件。


0
投票

首先,我建议使用以下内容来阅读台词。这将删除您的 if/else 条件(我不确定您为什么使用它):

    with open(filename) as f:
        lines = f.read().splitlines() 

此方法删除换行符,让您轻松阅读每一行中的单词,而不必担心副案例。这将返回一个字符串列表,其中每个项目都是文档中的一行。

此外,您可以使用

in
运算符来使您的代码更易于调试,而不是单独检查每个元音。所以,这样的事情会起作用:

for word in line:
   for letter in word:
       if letter.lower() in ['a', 'e', 'i', 'o', 'u']:
           vowels += 1

现在,你所要做的就是实现你已经拥有的,并想出一种方法来读取文件,遍历文件中的每一行,然后遍历每个单词并使用上面的 for 循环来获取元音的数量.

© www.soinside.com 2019 - 2024. All rights reserved.