PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 29, 2022

[FIXED] How to find the frequency of words in a list created from a .csv file

 August 29, 2022     csv, list, python, word-frequency     No comments   

Issue

I am trying to 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 should output the words and their frequencies (the number of times each word appears in the file) without any duplicates.

The file input1.csv has hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy

So far I have this:

import csv
with open('input1.csv', 'r') as wordsfile:
words_reader = csv.reader(wordsfile)
for row in words_reader:
    for word in row:
        count = row.count(word)
        print(word, count)

But my output is this: "hello 1 cat 2 man 2 hey 2 dog 2 boy 2 Hello 1 man 2 cat 2 woman 1 dog 2 Cat 1 hey 2 boy 2"

I am trying to output this but without any duplicates, I'm stumped and any help would be appreciated.


Solution

Try using set()

import csv
with open('input1.csv', 'r') as wordsfile:
words_reader = csv.reader(wordsfile)
for row in words_reader:
    list_of_words = set(row)
    for word in list_of_words:
        count = row.count(word)
        print(word, count)

I am not very familiar with csv library and I dont know if row is a list or not so sorry if this throws an error. If row is a string probably you can use

row = row.split()
list_of_words = set(row)

Hope it helps.



Answered By - Aryman Deshwal
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing