I've got a basic python function that I've been tasked with finishing in a class.
It's already fulfilling all the requirements for an A as it's an introductory course to Python, but I'd like to get some advice on it still as it's taking quite some time to execute.
I've got a few years of experience with general programming, but I'm still quite new to Python. As such any sort of advice on what might be taking up time would be appreciated.
As it stands at the moment, it takes about .5 seconds to run through the code and print all the data.
A bit of detail to the program:
It reads three files:
- A part of Alice in the Wonderland's first chapter (alice-ch1.txt)
- A list of common words (common-words.txt)
- And a list of correctly spelt words.
- Finally it prints the top 7 words that have passed through the filters.
def analyse():
#import listdir
from os import listdir
#import counter
from collections import Counter
files = "*************************************\n"
for file in listdir():
if file.endswith('.txt'):
files = files + file + "\n"
choice = input("These are the files: \n" + files + "*************************************\nWhat file would you like to analyse?\n")
if choice.strip() == "":
choice = "alice-ch1.txt"
elif choice.endswith(".txt"):
print(choice)
else:
choice = choice + ".txt"
print(choice)
with open(choice) as readFile, open('common-words.txt') as common, open('words.txt') as correct:
correct_words = correct.readlines()
common_words = common.readlines()
common_words = list(map(lambda s: s.strip(), common_words))
correct_words = list(map(lambda s: s.strip(), correct_words))
words = [word for line in readFile for word in line.split()]
for word in list(words):
if word in common_words or not word in correct_words:
words.remove(word)
print("There are " + str(len(words)))
c = Counter(words)
#for word, count in c.most_common():
# print (word, count)
nNumbers = list(c.most_common(7))
out = ""
print("*************************************\nThese are the 7 most common:")
for word, count in nNumbers:
out = out + word + "," + str(count) + "\n"
print(out + "\n*************************************")
input("\nPress enter to continue...")