Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8476135
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T18:05:46+00:00 2026-06-10T18:05:46+00:00

I’ve seen a bunch of posts that do basically what I’m doing, but unfortunately

  • 0

I’ve seen a bunch of posts that do basically what I’m doing, but unfortunately I’m not sure why I keep getting output that is not what I want. The problem is that I am trying to increment a dictionary every time a certain word appears in my excel file, but every instance of a word is treated as a new word as my code currently is. For example “the” occurs ~50 times in my file, but the output just lists “the” on many different lines with a count of “1” for each instance. When in reality I want “the” to be listed once, with a count of “50”. Would greatly appreciate any clarification! Here is my code:

import csv
import string

filename = "input.csv"
output = "output1.txt"

def add_word(counts, word):
    word = word.lower()
    #the problem is here, the following line never runs
    if counts.has_key(word):
        counts[word] +=1
    #instead, we always go to the else statement...
    else:
        counts[word] = 1
    return counts

def count_words(text):
    word = text.lower()
    counts = {}
    add_word(counts, word)
    return counts

def main():
    infile = open(filename, "r")
    input_fields = ('name', 'country')
    reader = csv.DictReader(infile, fieldnames = input_fields)
    next(reader)
    first_row = next(reader)
    outfile = open(output, "w")
    outfile.write("%-18s%s\n" %("Word", "Count"))
    for next_row in reader:
        full_name = first_row['name']
        word = text.split(' ',1)[0]
        counts = count_words(word)
        counts_list = counts.items()
        counts_list.sort()
        for word in counts_list:
            outfile.write("%-18s%d\n" %(word[0], word[1]))
        first_row = next_row

if __name__=="__main__":
main()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T18:05:48+00:00Added an answer on June 10, 2026 at 6:05 pm

    Using plain dictionaries, the dict.get method is well suited to counting:

    >>> d = {}
    >>> for color in 'red green blue green red red green'.split():
            d[color] = d.get(color, 0) + 1
    
    >>> d
    {'blue': 1, 'green': 3, 'red': 3}
    

    The collections module offers two ways of simplifying this code.

    Here’s one using collections.Counter

    >>> from collections import Counter
    >>> d = Counter()
    >>> for color in 'red green blue green red red green'.split():
            d[color] += 1
    
    >>> d
    Counter({'green': 3, 'red': 3, 'blue': 1})
    

    And there is the collections.defaultdict approach:

    >>> from collections import defaultdict
    >>> d = defaultdict(int)
    >>> for color in 'red green blue green red red green'.split():
            d[color] += 1
    
    >>> d
    defaultdict(<type 'int'>, {'blue': 1, 'green': 3, 'red': 3})
    

    The regular dictionary approach is most suitable when your output needs to be a regular dictionary or when you’re using an older version of Python.

    The Counter approach is easy-to-use and has a number of utilities well-suited to counting applications (for example, the most_common() method lists the n biggest counts in sorted order). A backport of Counter is available for versions of Python prior to 2.7.

    The defaultdict approach has some disadvantages. Merely accessing a missing value will cause the dictionary to grow. Also, to use it, you need to understand factory functions and know that int() can be called with no arguments to produce a zero value.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a French site that I want to parse, but am running into
I want to count how many characters a certain string has in PHP, but
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
I want to construct a data frame in an Rcpp function, but when I
I have a bunch of posts stored in text files formatted in yaml/textile (from
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
Basically, what I'm trying to create is a page of div tags, each has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.