Feb-17-2020, 03:30 PM
This is my code. I tried to open a file and count keywords, which I setup before, as "{keyword}: {occurrence}",. But I get wrong result, the ouput is double or more times of occurrence of keywords. Does any one know why I made the error and how to fix it? Thanks so much!
import os.path
import sys
def main():
counting = {}
KeyWords = {'and', 'as', 'assert', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else',
'except', 'False', 'finally', 'for', 'from',
'globe', 'if', 'import', 'in', 'is', 'lambda',
'None', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'True', 'try', 'while', 'with', 'yield'}
filename = input("Enter a Python source code filename: ").strip()
if not os.path.isfile(filename):
print("File", filename, "does not exist.")
sys.exit()
infile = open(filename, 'r')
text = infile.read().split()
count = 0
for word in text:
if word in KeyWords:
count += 1
counting[word] = count
print(counting)
for key, value in counting.items():
print(f"-{key}: {value}")
main()
import os.path
import sys
def main():
counting = {}
KeyWords = {'and', 'as', 'assert', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else',
'except', 'False', 'finally', 'for', 'from',
'globe', 'if', 'import', 'in', 'is', 'lambda',
'None', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'True', 'try', 'while', 'with', 'yield'}
filename = input("Enter a Python source code filename: ").strip()
if not os.path.isfile(filename):
print("File", filename, "does not exist.")
sys.exit()
infile = open(filename, 'r')
text = infile.read().split()
count = 0
for word in text:
if word in KeyWords:
count += 1
counting[word] = count
print(counting)
for key, value in counting.items():
print(f"-{key}: {value}")
main()