0

Hello for my class assignment, I have to write a script that will import an csv file, then read the words in the file, count the frequency of each word and print out the list of the words with the frequency count. My problem is that I have to be able to open any given csv file. When I submit the assignment, the program will check if my script can open "input1.csv, input2.csv, input3.csv" and etc. I am having a hard time searching the web to figure out how to have open() open any give file and not just one preset file.

actual assignment: "Write a program that first reads in the name of an input file and then reads the file using the csv.reader() method. The file contains a list of words separated by commas. Your program should output the words and their frequencies (the number of times each word appears in the file) without any duplicates."

# Have to import the file type
import csv

# I have words and new_words set as list
words = []
new_words = []

# Open the file with read
with open('input1.csv, 'r') as csvfile:
    # Then read the file
    reader = csv.reader(csvfile, delimiter = ',')
    
    # the for loop will check for the words in the row then add them to list
    for row in reader:
        for word in row:
            words.append(word)
            
        # Next the for loop with check how many times the word is in the list
        for word in words:
            freq = words.count(word)
            
            # if the word is not in new_word it will append it to word. This allows to not have duplicated words
            if word not in new_words:
                new_words.append(word)
                # Print the word plus the count
                print(word, freq)
Joe
  • 15
  • 4

0 Answers0