Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help for code
#1
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()
Reply
#2
Please use the python tag to show your code, it makes it easier to view and follow.

Originally posted by: Frank12347

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()
"Often stumped... But never defeated."
Reply
#3
You don't reset count for each keyword
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020