📜  计算文本文件中元音、行、字符的Python程序

📅  最后修改于: 2022-05-13 01:55:17.024000             🧑  作者: Mango

计算文本文件中元音、行、字符的Python程序

在本文中,我们将创建一个Python程序,用于计算特定文本文件中存在的元音、行和字符数。

方法

  • 我们必须使用Python中的open()函数打开文件。
  • 然后制作三个变量,元音、行和字符,分别统计元音、行和字符的个数。
  • 制作一个元音列表,以便我们可以检查字符是否为元音。
  • 当计数达到 '\n'字符时,我们必须增加行变量意味着文件中的新行。
  • 之后迭代文件的字符并计算元音、行和字符。

以下是完整的实现:

Python3
# Python program to count number of vowels,
# newlines and character in textfile
  
def counting(filename):
    
    # Opening the file in read mode
    txt_file = open(filename, "r")
  
    # Initialize three variables to count number of vowels,
    # lines and characters respectively
    vowel = 0
    line = 0
    character = 0
  
    # Make a vowels list so that we can
    # check whether the character is vowel or not
    vowels_list = ['a', 'e', 'i', 'o', 'u',
                   'A', 'E', 'I', 'O', 'U']
  
    # Iterate over the characters present in file
    for alpha in txt_file.read():
        
        # Checking if the current character is vowel or not
        if alpha in vowels_list:
            vowel += 1
              
        # Checking if the current character is
        # not vowel or new line character
        elif alpha not in vowels_list and alpha != "\n":
            character += 1
              
        # Checking if the current character
        # is new line character or not
        elif alpha == "\n":
            line += 1
  
    # Print the desired output on the console.
    print("Number of vowels in ", filename, " = ", vowel)
    print("New Lines in ", filename, " = ", line)
    print("Number of characters in ", filename, " = ", character)
  
  
# Calling the function counting which gives the desired output
counting('Myfile.txt')


输出:

Number of vowels in  MyFile.txt  =  23    
New Lines in  MyFile.txt  =  2
Number of characters in  MyFile.txt  =  54

文本文件: