59.2k views
4 votes
The csv file contain the follwing row

hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy


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. The program must output the words and their frequencies (the number of times each word appears in the file) without any duplicates.

use this as a start:
import csv

def read_file(user_file):
# write your code here
pass


file_name = input()

word_lst = read_file(file_name)

print(word_lst)







I want the code that will be written to pass the test code:

import os
import sys
import subprocess,glob
import ntpath
import re
import types
import ast
import builtins
import csv

instructor = False

def test_part1(read_file):

grade1 = 0

try:
v = read_file('input1.csv')
if v[0] == 'hello' and v[1] == 1 and v[2]== 'cat' and v[3]== 2 and v[16]== 'Cat' and v[17]== 1:
grade1 += 25
print(f'test .... pass')
else:
print(f'test .... fail')
except Exception as ex:
pass


return grade1


def test_part2(get_name):

grade2 = 0

names = ['Ryley', 'Edan', 'Reagan', 'Henry', 'Caius', 'Jane', 'Guto', 'Sonya', 'Tyrese', 'Johnny']
index = 5
try:
output = get_name(names,index)
if output == 'Jane':
grade2 += 5
print(f'test with index {index}.... pass')
else:
print(f'test with input {index}.... fail')
except Exception as ex:
pass

try:
index = 12
output = get_name(names,index)
if output == 'Johnny':
grade2 += 5
print(f'test with index {index}.... pass')
else:
print(f'test with input {index}.... fail')
except Exception as ex:
pass

try:
index = -15
output = get_name(names,index)
if output == 'Ryley':
grade2 += 2.5
print(f'test with index {index}.... pass')
else:
print(f'test with input {index}.... fail')
except Exception as ex:
pass

try:
index = -2
output = get_name(names,index)
if output == 'Tyrese':
grade2 += 2.5
print(f'test with index {index}.... pass')
else:
print(f'test with input {index}.... fail')
except Exception as ex:
pass



return grade2

def test():

files = glob.glob('lab6-*.ipynb')

grades = []
stud_nums = []
error = []

for fn in files:

basename = os.path.splitext(os.path.basename(fn))[0]
stud_num = basename.split('-')[1]
lab_name = basename.split('-')[0]

with open('notebook.py', 'w') as outputFile:
subprocess.call(['jupyter', 'nbconvert', '--to', 'script',
fn, '--stdout'], stdout=outputFile)

#tree = ast.parse(open(fn).read(), 'eval')
with open('notebook.py') as fp:
tree = ast.parse(fp.read(), 'eval')

for node in tree.body[:]:
if (not isinstance(node, ast.FunctionDef) and not isinstance(node, ast.Import)
and not isinstance(node, ast.ImportFrom)):
tree.body.remove(node)
module = types.ModuleType(basename)
#print(module.__dict__)
# use compile to exec multi-line
code = compile(tree,fn, 'exec')
sys.modules['basename'] = module
exec(code,module.__dict__)


from basename import read_file
import math

print('='*20)
print(f'Word frequencies')
print('='*20)

grade = test_part1(read_file)

grades.append(grade)
stud_nums.append(stud_num)

return stud_nums,grades,lab_name

if __name__ == "__main__":

num, grade,lab_name = test()


if instructor:
import pandas as pd

print('='*40)
print(f'Student ID\t\t' + f'Grade')
print('='*40)

for i in range(len(num)):
print(f'{num[i]}\t\t\t' + f'{grade[i]}')


df = pd.DataFrame(list(zip(num,[float(x) for x in grade])),columns =['Student ID', 'Grade'])
df.to_excel(f'{lab_name}.xlsx')

else:
print('='*40)
print(f'Student ID\t\t' + f'Grade')
print(f'{num[0]}\t\t\t' + f'{grade[0]}')
print('='*40)

User Jts
by
8.8k points

1 Answer

4 votes

Answer:

import csv

def read_file(user_file):

word_dict = {}

with open(user_file) as file:

reader = csv.reader(file)

for row in reader:

for word in row:

if word in word_dict:

word_dict[word] += 1

else:

word_dict[word] = 1

word_lst = []

for key, value in word_dict.items():

word_lst.append(key)

word_lst.append(value)

return word_lst

file_name = input()

word_lst = read_file(file_name)

print(word_lst)


Step-by-step explanation:

This code reads the input file using the csv.reader() method and counts the frequency of each word using a dictionary. The words and their frequencies are then added to a list and returned. This code should pass the test code you provided.

User Issa Marie Tseng
by
8.2k points