Question

(Count the occurrences of each keyword) Write a python program that reads in a Python source...

(Count the occurrences of each keyword) Write a python program that reads in a Python source code file and counts the occurrence of each keyword in the file. Your program should prompt the user to enter the Python source code filename.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#!/usr/bin/env python3
"""Count the occurrences of each keyword
Write a program that reads in a Python source code file and counts the
occurrence of each keyword in the file.
Your program should prompt the user to enter the Python source code
filename.
"""
import os
from counter import Counter

keywords = """
and       del       from      not       while
as        elif      global    or        with
assert    else      if        pass      yield
break     except    import    print
class     exec      in        raise
continue finally   is        return
def       for       lambda    try
"""

if __name__ == "__main__":
    filename = input('Enter filename: ')
    keywords = keywords.split()
    if os.path.isfile(filename):
        with open(filename, 'r') as f:
            data = f.read().split()
            C = Counter(data, keywords)
            matched = C.collection
            f.closed
            for item in matched.items():
                print('Keyword "{}" occur {} times'.format(
                    item[0], item[1]
                ))
    else:
        print('File "{}" does not exist!'.format(filename))
      
      
Counter.py

#!/usr/bin/env python3

class Counter:

    def __init__(self, data, pattern=None):
        self.data = tuple(data)
        self.pattern = [str(i) for i in pattern] if pattern else None
        self.collection = dict()
        if self.pattern:
            self.matching()
        else:
            self.count()

    def count(self):
        # if data is string or list
        for item in self.data:
            item = str(item) # just for consistency
            if item in self.collection:
                self.collection[item] += 1
            else:
                self.collection[item] = 1

    def matching(self):
        # if data is string or list
        for item in self.data:
            item = str(item) # just for consistency
            if item in self.pattern:
                if item in self.collection:
                    self.collection[item] += 1
                else:
                    self.collection[item] = 1

    def duplicates(self):
        c = self.collection
        return {i:c[i] for i in c if c[i] > 1}

    def uniques(self):
        c = self.collection
        return {i:c[i] for i in c if c[i] == 1}

Add a comment
Know the answer?
Add Answer to:
(Count the occurrences of each keyword) Write a python program that reads in a Python source...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a program that reads a Java source-code file and reports the number of keywords (including...

    Write a program that reads a Java source-code file and reports the number of keywords (including null, true, and false) in the file. If a keyword is in a comment or in a string, don’t count it. Test your program to count the keywords in the Welcome.java file: Please input the Java filename: Welcome.java The number of keywords in the program is 6

  • 1. Write a python program that reads a file and prints the letters in increasing order...

    1. Write a python program that reads a file and prints the letters in increasing order of frequency. Your program should convert entire input to lower case and only counts letters a-z. Special characters or spaces should not be counted. Each letter and it's occurrences should be listed on a separate line. 2. Test and verify your program and it's output. ---Please provide a code and a screenshot of the code and output. Thank you. ----

  • In Python 3, Write a program that reads in a text file that consists of some...

    In Python 3, Write a program that reads in a text file that consists of some standard English text. Your program should count the number of occurrences of each letter of the alphabet, and display each letter with its count, in the order of increasing count. What are the six most frequently used letters?

  • Write a program that reads integers, finds the smallest of them, and counts its occurrences. Assume...

    Write a program that reads integers, finds the smallest of them, and counts its occurrences. Assume that the input ends with number -1. Suppose that you entered 4 2 9 2 2 -1; the program finds that the smallest is 2 and the occurrence count for 2 is 3. (Hint: Maintain two variables, min and count. min stores the current min number, and count stores its occurrences. Initially, assign the first number to min and 1 to count. Compare each...

  • Write a PYTHON program that reads a file (prompt user for the input file name) containing...

    Write a PYTHON program that reads a file (prompt user for the input file name) containing two columns of floating-point numbers (Use split). Print the average of each column. Use the following data forthe input file: 1   0.5 2   0.5 3   0.5 4   0.5 The output should be:    The averages are 2.50 and 0.5. a)   Your code with comments b)   A screenshot of the execution Version 3.7.2

  • Character Count Write a program that reads a file and counts the number of occurrences of...

    Character Count Write a program that reads a file and counts the number of occurrences of each character in the file (case sensitive). The file name is "char.txt". You should use a dictionary to hold the number of occurrences of each character, and print out that dictionary. For example, if the file contains only six characters, "tactic", your dictionary should contain the following key-value pairs (order can be different): {'a': 1, 'c': 2, 'i': 1, 't': 2} Sample Input: Follow...

  • In C++ Sorted List of User Entered Numbers 2. Write a program that reads in a...

    In C++ Sorted List of User Entered Numbers 2. Write a program that reads in a list of integers into a vector with base type int. Provide the facility to read this vector from an input file. Make sure to ask the user for a filename. The output is a two-column list. The first column is a list of the distinct vector elements. The second column is the count of the number of occurrences for each element. The list should...

  • JAVA Code: Complete the program that reads from a text file and counts the occurrence of...

    JAVA Code: Complete the program that reads from a text file and counts the occurrence of each letter of the English alphabet. The given code already opens a specified text file and reads in the text one line at a time to a temporary String. Your task is to go through that String and count the occurrence of the letters and then print out the final tally of each letter (i.e., how many 'a's?, how many 'b's?, etc.) You can...

  • (Count occurrence of numbers) Write a program that reads some integers between 1 and 100 and...

    (Count occurrence of numbers) Write a program that reads some integers between 1 and 100 and counts the occurrences of each. Here is a sample run of the program: Enter integers between 1 and 100: 2 occurs 2 times 3 occurs 1 time 4 occurs 1 time 5 occurs 2 times 6 occurs 1 time 23 occurs 1 time 43 occurs 1 time 2 5 6 5 4 3 23 43 2 Note that if a number occurs more than...

  • Count Occurrences in Seven Integers Using Java Single Dimension Arrays In this assignment, you will design...

    Count Occurrences in Seven Integers Using Java Single Dimension Arrays In this assignment, you will design and code a Java console application that reads in seven integer values and prints out the number of occurrences of each value. The application uses the Java single dimension array construct to implement its functionality. Your program output should look like the sample output provided in the "Count Occurrences in Seven Integers Using Java Single Dimension Arrays Instructions" course file resource. Full instructions for...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT