PYTHON HOMEWORK! Please help (Count the occurrences of each keyword) Write a pyt
ID: 3576069 • Letter: P
Question
PYTHON HOMEWORK!
Please help
(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. The program should prompt the user to enter the Python source code filename.
I have the sample code. However, the sample code only count the number of keywords, without breaking the occurence of each keyword.
import os path import sys def main O keywords and ''as'', assert "break" class Continue "def", "del ''elif", else except "False "finally "for "from global "if", import "in", "is", am "None", nonlocal not "or", pass "raise" return "True try while with" yield'' filename input "Enter a Python source code filename: strip if not oss path isfile (filename) Check if file exists print "File filename "does not exist") sys exito infile open filename, "r") open files for input text infile. read (C) split() Read and split words from the file Count 0 for word in text: if word in keywords: count print "The number of keywords in filename "is", count) main()Explanation / Answer
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}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.