Python Forum
Help with infile questions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with infile questions
#1
1. Write a function, countWords(ifile) which takes an input file, ifile, and counts the number of occurrences for each word in the file. You must remove all punctuation except apostrophes. Return the sorted list of unique words and the count of the number of occurrences in that file.


4. Write a function, makeTable(ifile,ofile) which will take its input from ifile. Each line in the ifile is as follows. You must use the .format command for the table and average.

A string which includes leading and trailing spaces
A floating point number
A string which includes leading and training spaces
Reply
#2
Please, Make an attempt at writing code,
Show what you've written
Then if you have a question, we'll be glad to help
Reply
#3
I'm having a hard time figuring these two out. I'm not a computer science major so I know this code probably looks bad. That being said, here's what I got so far on the first function

def countWords(ifile): infile = open(ifile,'r') lst2 = list() count = infile.count(word) if word not in lst2: lst2.append(word) lst2.append(count) return lst2

def countWords(ifile):
    infile = open(ifile,'r') 
    lst2 = list()
    count = infile.count(word)
    if word not in lst2:
        lst2.append(word)
        lst2.append(count)
     return lst2
and the second function I'm just entirely confused on
Reply
#4
Please read BBCODE
Can't see indentation otherwise


You need to use split, to split each sentence into words
you do that like my_list = infile.readline()

to get started:
def countWords(ifile):
    infile = open(ifile,'r')
    text = infile.read()
    text = text.split()
    count = len(text)
    print('count: {}'.format(count))
now write the code to remove aphostrophies, etc.
don't forget to close the file
Reply


Forum Jump:

User Panel Messages

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