Python Forum
Need help for code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Need help for code (/thread-24507.html)



Need help for code - Frank12347 - Feb-17-2020

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()


RE: Need help for code - DT2000 - Feb-17-2020

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()



RE: Need help for code - jefsummers - Feb-17-2020

You don't reset count for each keyword