In Python write a program that prompts the user for a file name, make sure the file exists and if it does reads through the file, count the number of times each word appears and then output the word count in a sorted order from high to low.
The program should:
the - 7
in - 6
to - 5
and - 4
of - 4
Remember:
NYT2.txt file below:
Fact-Checking Trump’s Orlando Rally: Russia, the Wall and Tax Cuts President Trump delivered remarks in Florida in a formal start to his re-election effort. Deutsche Bank Faces Criminal Investigation for Potential Money-Laundering Lapses Federal authorities are focused on whether the bank complied with anti-money-laundering laws, including in its review of transactions linked to Jared Kushner. Five NY1 Anchorwomen Sue Cable Channel for Age and Gender Discrimination The women, including Roma Torre, say their careers were derailed after Charter Communications bought New York’s hometown news station in 2016. Hypersonic Missiles Are Unstoppable. And They’re Starting a New Global Arms Race. The new weapons — which could travel at more than 15 times the speed of sound with terrifying accuracy — threaten to change the nature of warfare. Nxivm’s Keith Raniere Convicted in Trial Exposing Sex Cult’s Inner Workings Mr. Raniere set up a harem of sexual “slaves” who were branded with his initials and kept in line by blackmail. Jamal Khashoggi Was My Fiancé. His Killers Are Roaming Free. Washington hasn’t done enough to bring the murdered Saudi columnist’s killers to justice.
If you have any doubts, please give me comment...
import string
def countWords(fname):
words = {}
fp = open(fname, "r")
for line in fp.readlines():
line = line.lower().translate(str.maketrans('','', string.punctuation))
for w in line.split():
if w not in words:
words[w] = 0
words[w] += 1
fp.close()
return words
fname = input("Enter file: ")
frequency = countWords(fname)
sorted_frequency = sorted(frequency.items(), key = lambda kv:(kv[1], kv[0]), reverse=True)
for (word, freq) in sorted_frequency[:5]:
print(word+" : "+str(freq))
Get Answers For Free
Most questions answered within 1 hours.