Write a program to count frequency of characters in a given file in python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In this article, we will be learning different approaches to count the number of times a letter appears in a text file in Python. Below is the content of the text file gfg.txt that we are going to use in the below programs:

    Now we will discuss various approaches to get the frequency of a letter in a text file.

    Method 1: Using the in-built count[] method.

    Approach:

    • Read the file.
    • Store the content of the file in a variable.
    • Use the count[] method with the argument as a letter whose frequency is required.
    • Display the count of the letter.

    Implementation:

    Python3

    def letterFrequency[fileName, letter]:

        file = open[fileName, 'r']

        text = file.read[]

        return text.count[letter]

    print[letterFrequency['gfg.txt', 'g']]

    Output:

    Method 2: Iterate through the file content in order to compare each character with the given letter.

    Approach:

    • Read the file.
    • Store the content of the file in a variable.
    • Assign a counter count variable with 0.
    • Iterate through each character, if the character is found to be the given letter then increment the counter.
    • Display the count of the letter.

    Implementation:

    Python3

    def letterFrequency[fileName, letter]:

        file = open[fileName, "r"]

        text = file.read[]

        count = 0

        for char in text:

            if char == letter:

                count += 1

        return count

    print[letterFrequency['gfg.txt', 'g']]

    Output:


    Ques . WAP to count frequency of characters in a given file.Can u use character frequency to test whether the given file is Python program file, C program file or a text file

    Answer : 

    Program -1

    f="C:\\Users\\HP\\Desktop\\g.txt"

    file = open [ f, "r" ]

    a=[]

    b={}

    for i in file:

        for j in range[0,len[i]]:

            a.append[i[j]]

    for i in a:

        if i in b:

            b[i]+=1

        else:

            b[i]=1

    print[b]

    c=f.split["."]

    if c[1]=="txt":

        print["\n\nit is a text file"]

    elif c[1]=="cpp":

        print["\n\nit is a c++ file"]

    else:

        print["\n\nit is a c file"]

    Output 1 : 

    {'g': 2, 'o': 7, 'e': 12, 'd': 4, 'u': 5, 'h': 1, 'b': 1, ' ': 13, 'w': 4, 'l': 3, 'c': 1, 'm': 3, 's': 4, 'y': 1, '!': 3, '\n': 2, 'p': 2, 'r': 7, 'v': 2, 'i': 7, 'f': 1, 'n': 6, 't': 4, 'a': 3}

    it is a text file

    Program 2 :

    import collections

    import pprint

    file_input = "D:\\Komal\\n1\\goeduhub\\python.txt"

    with open[file_input, 'r'] as info:

      count = collections.Counter[info.read[].upper[]]

      value = pprint.pformat[count]

    print[value]

    a=file_input.split["."]

    if a[1]=="txt":

        print["it is a text file"]

    elif a[1]=="cpp":

        print["it is a c++ file"]

    else:

        print["it is a c file"]

     Output 2 :

    Counter[{' ': 25,

             'E': 21,

             'I': 16,

             'N': 16,

             'O': 15,

             'T': 12,

             'S': 11,

             'L': 10,

             '.': 9,

             'U': 8,

             'R': 8,

             'A': 8,

             'W': 7,

             'D': 6,

             ',': 6,

             'G': 5,

             'H': 5,

             'M': 5,

             'V': 5,

             'C': 4,

             'P': 4,

             '\n': 3,

             'Q': 3,

             'F': 2,

             '1': 1,

             'B': 1,

             '2': 1,

             '3': 1,

             'Y': 1,

             '4': 1}]

    it is a text file

    For more Rajasthan Technical University CSE VI Sem Python Lab Experiments Click here

    How do you count the frequency of each character in a string in Python?

    count[] coupled with set[] can also achieve this task, in this we just iterate over the set converted string and get the count of each character in original string and assign that element with that value counted using count[] .

    How do you count characters in a file in Python?

    Example 1: Count Characters in a Text File.
    Text File. ... .
    Python Program #open file in read mode file = open["C:\data.txt", "r"] #read the content of file data = file.read[] #get the length of the data number_of_characters = len[data] print['Number of characters in text file :', number_of_characters].

    How do you count the frequency of words in a Python file?

    Python File I/O: Count the frequency of words in a file.
    Contain of text.txt. ... .
    Sample Solution:-.
    Python Code: from collections import Counter def word_count[fname]: with open[fname] as f: return Counter[f.read[].split[]] print["Number of words in the file :",word_count["test.txt"]] ... .
    Flowchart:.
    Python Code Editor:.

    How do I count the number of characters in a text file?

    The most easiest way to count the number of lines, words, and characters in text file is to use the Linux command “wc” in terminal. The command “wc” basically means “word count” and with different optional parameters one can use it to count the number of lines, words, and characters in a text file.

    Chủ Đề