This is a Python problem. Still an intro course and I need some guidance on how
ID: 3693534 • Letter: T
Question
This is a Python problem. Still an intro course and I need some guidance on how to approach/do this. Thanks in advance!
2. (File Output, 10pt) Your goal in the problem is to write a functions days(fname) that counts how often each weekday is mentioned in the textfile with name fname, and writes the result to a logfile with name fname_daycount.txt (where fname is replaced by the atual filename). For example, I ran days(innocents.txt'), and it created the following text-file (you can see the name of the file at the top). Use a loop for the writing, do not create seven separate write statements. innocents.txt daycount.tt- Notepacd File Edit Format View Help Monday is mentioned 4 times in innocents.txt Tuesday is mentioned 3 times in innocents.txt wednesday is mentioned 2 times in innocents.txt Thursday is mentioned 3 times in innocents.txt Friday is mentioned 7 times in innocents.txt Saturday is mentioned 9 times in innocents.txt sunday is mentioned 17 times in innocents.txt Hint: Use count on the full text (no need to split, though you can), and don't worry about case (so case- sensitive is fine here). You can also test your program on the other texts: innocents.txt, sawyer.txt, roughing.txt, stranger.txt. For the filename: initially hardcode a name like 'daycount.txt', and then think about how to include fname in the name of the file you write. ov to inude fhame in the namerr he ynmte dnaceni aasExplanation / Answer
#python code to count the occurence of weekdays in a file
import re
def days(filename):
# Open a file
fo = open(outputfilename, "wb")
fh = open(filename, "r+")
#reading file to string
str = fh.read()
str = str.lower()
words = str.split()
print words
#counting the days in weekdays
count_monday = words.count("monday")
count_tuesday = words.count("tuesday")
count_wednesday = words.count("monday")
count_thursday = words.count("monday")
count_friday = words.count("friday")
count_saturday = words.count("monday")
count_sunday = words.count("monday")
#writing to file
print >> fo, "monday is mentioned ", count_monday , "times in" , filename, " "
print >> fo, "tuesday is mentioned ", count_tuesday , "times in" , filename, " "
print >> fo, "wednesday is mentioned ", count_wednesday , "times in" , filename, " "
print >> fo, "thursday is mentioned ", count_thursday , "times in" , filename, " "
print >> fo, "friday is mentioned ", count_friday , "times in" , filename, " "
print >> fo, "saturday is mentioned ", count_saturday , "times in" , filename, " "
print >> fo, "sunday is mentioned ", count_sunday , "times in" , filename, " "
# Close opend file
fo.close()
fh.close()
days(inputfile)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.