r/dailyprogrammer • • Dec 01 '14
[2014-12-1] Challenge #191 [Easy] Word Counting
You've recently taken an internship at an up and coming lingustic and natural language centre. Unfortunately, as with real life, the professors have allocated you the mundane task of counting every single word in a book and finding out how many occurences of each word there are.
To them, this task would take hours but they are unaware of your programming background (They really didn't assess the candidates much). Impress them with that word count by the end of the day and you're surely in for more smooth sailing.
Description
Given a text file, count how many occurences of each word are present in that text file. To make it more interesting we'll be analyzing the free books offered by Project Gutenberg
The book I'm giving to you in this challenge is an illustrated monthly on birds. You're free to choose other books if you wish.
Inputs and Outputs
Input
Pass your book through for processing
Output
Output should consist of a key-value pair of the word and its word count.
Example
{'the' : 56,
'example' : 16,
'blue-tit' : 4,
'wings' : 75}Clarifications
For the sake of ease, you don't have to begin the word count when the book starts, you can just count all the words in that text file (including the boilerplate legal stuff put in by Gutenberg).
Bonus
As a bonus, only extract the book's contents and nothing else.
Finally
Have a good challenge idea?
Consider submitting it to /r/dailyprogrammer_ideas
Thanks to /u/pshatmsft for the submission!
16
u/thestoicattack Dec 01 '14 edited Dec 01 '14
bash:
EDIT: to get, say, the top 10:
result:
12
u/AdrianOkanata Dec 01 '14
One line of ruby:
11
u/thinksInCode Dec 02 '14
Java 8:
8
u/jnazario 2 0 Dec 01 '14 edited Dec 02 '14
F#. regex-ing for words made this a lot easier than my original way of stripping character classes away after splitting.
7
u/dongas420 Dec 01 '14 edited Dec 02 '14
Perl:
7
u/djinzoo Dec 08 '14 edited Dec 09 '14
C++. One of the first programs I have made.
5
u/Godspiral 3 3 Dec 01 '14 edited Dec 01 '14
In J, with variable 'a' holding the text, and the J language's definition of a word (the the. and the: are different words).
first 10 words in text count
top 20 "word" counts (with line feeds and appostrophe's removed)
3
u/drizzlelicious Dec 02 '14
JavaScript + node.js
3
u/mesonoxianlurker Dec 02 '14
python3:
2
u/[deleted] Dec 01 '14
Rust. This took all freaking day. Don't tell the boss.
2
u/pshatmsft 0 1 Dec 01 '14
PowerShell. It's really a one-liner....
But here it is as a function...
And the first few lines of output
2
u/hansq Dec 02 '14
C#
2
u/ghillisuit95 Dec 02 '14
Lots of great submissions here, with a lot of cool one-liners. although I am suprised to see nobody used a trie: http://en.wikipedia.org/wiki/Trie as it was my first thought when I read the challenge
2
u/LoveOfProfit Dec 02 '14 edited Dec 02 '14
First time posting here, utter Java noob, but I recently did exactly this in my intro to Java class, so here was my solution (incredibly lengthy and poor compared to most solutions here). We were to implement our own binary search tree using a map to store key value pairs. It's not perfect by any stretch of the imagination and the final word counts are a bit off, but I really enjoyed it as I learned a ton and many things clicked into place (more so about maps and binary search trees than the word counting itself). It was the first project where by the end I felt I kind of had an idea of what I was doing.
We had previously created our own implementations of doubly linked lists from scratch, so we were allowed to simply use Java's List without redoing that on our own.
Interfaces:
Implementations:
Map:
FileCount implementation:
Tested with:
2
u/scubasteve2012 1 0 Dec 02 '14 edited Dec 02 '14
C# using Linq and Regex (Top 10 words). Feedback welcome:
2
u/Maping Dec 03 '14
Here's my Java solution. I seem to be getting some different results, so I may have messed up somewhere.
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner;
}
And top 20 results:
2
u/petethemonkey Dec 03 '14
Python 3
2
u/mpatraw Dec 03 '14
Here's a C implementation using a custom hash table and qsort. It's fairly quick, but there's definitely room for improvement: https://gist.github.com/mpatraw/97b8fb1167dcde02f4d9
2
u/[deleted] Dec 03 '14
Standard C++, taking a file as an argument.
It handles the entire book too fast to really notice, even with no optimisation.
I feel structure to find the start and end of the book is a little inelegant, but oh-well. Not bad for about half an hour's work, really.
include <iostream>
2
u/DanTheProgrammingMan Dec 03 '14
Ruby:
2
u/crashRevoke Dec 05 '14 edited Dec 05 '14
python 2.7, returns an ordered dict import string import sys import collections
2
u/sid_hottnutz Dec 05 '14
C# The bulk of the code is just for the console application to make it nice. This removes the Gutenberg copyright stuff and also accounts for punctuation and whatnot.
Edit: explained myself a bit more
2
u/[deleted] Dec 07 '14
A robust, object oriented program in Python 2.7 that does not rely on any modules to do anything except open the URL. It only extracts the books contents, and will return a list of tuples containing key/value pairs in descending order, without any duplicates or non alphabetic characters:
2
u/binaryblade Dec 07 '14
golang, could have been shorter but I went for a nice interface package main
2
u/wherethebuffaloroam Dec 09 '14 edited Dec 09 '14
I did this in snobol4
it's kinda cheating as &DUMP=1 causes snobol to just dump out its variables and values. The neat thing happens because I am generating variables based on the words that are found. Because I am generating variable names, i need to make sure that i don't overwrite the patterns that I'm using. That's why each pattern is prefaced with yyyVARIABLENAME as I consider this rare enough to never happen. I define a patter for word, grab one from a sentence and then make that variable incremented by one.
So if yyyword matches against a word like 'cardinal', then snobol makes a variable named cardinal and sets it to 1 or increments the variable cardinal by 1.
output looks like the following snippet:
2
u/adimit Dec 01 '14 edited Dec 21 '14
Haskell solution (it's a one-liner, of course. Well. Kind of. I split the line for readability.)
Now, the splitting function is essential here. If you just use
words, you're going to getfoo.foo,andfooas different tokens. You kinda don't want that, so instead ofwordsyou can define your own. Note that I'm usingTexthere — mainly for performance reasons. It also means that a highly performantwordsforTextthat tokenizes on punctuation, too, would have to mess withData.Text.Internal. Since this is rated easy, I won't do that here :-P Left as an exercise for the reader.1
u/lucaswerkmeister Dec 01 '14
Ceylon:
1
u/bbartek Dec 01 '14
Scala
1
u/metaconcept Dec 02 '14
Squeak Smalltalk. It probably won't work on other dialects.
Output:
1
u/[deleted] Dec 02 '14
My first ever submission to one of these. I'll figure out how to leave out the boilerplate stuff at the top later.
Python
1
u/[deleted] Dec 02 '14 edited Dec 22 '18
deleted 0.5285 What is ^^^this?
1
u/leonardo_m Dec 02 '14
D language. Instead of hashing, this uses sorting and grouping:
Output (for the whole txt version of "Illustrated monthly on birds"):
Edit: runtime is about 0.06 seconds with dmd compiler.
1
u/ReasonableCause Dec 02 '14
Here is my solution in Haskell; returns a sorted word count, most frequent words first:
Result (first 10 words):
1
u/tec5c Dec 02 '14
C#
1
u/jeaton Dec 02 '14
Shell:
1
u/-Robbie Dec 02 '14
Haskell
1
u/kahless62003 Dec 02 '14 edited Dec 04 '14
Plain C, made way too much of a meal of it and took way too long over it -edit(ditto on not telling the boss) and chose to do the tokening by hand and other things the hard way, but hopefully it is reasonably robust and versatile. It does have some bells and whistles like it can take the file name as an argument, so it should work with any file, and allows output redirection to a file, so here goes:
Output:
1
u/dhmmjoph Dec 02 '14
Python 2
1
u/cdkisa Dec 03 '14
VB.Net (top 50 words)
Output
====================================================== Time Taken: 1.390642 s
1
u/wizao 1 0 Dec 03 '14 edited Jan 30 '15
1
u/Atumm Dec 03 '14 edited Dec 03 '14
in the cmd line point a file as argument
example:
user@user-pc:python count_words.py ~/Desktop/cv.txt
TODO at more arguments like add your own words or chars to exclude or include
1
u/ddsnowboard Dec 04 '14 edited Dec 04 '14
Mine took more than one file, so here's the link to my github repo for these. It's a little lengthy, but I think it's simple to read, so that might make up for the length at least a little. EDIT: I forgot to say, it also does the bonus. Anyway, any constructive criticism is appreciated (for example, did I write a Counter class for no reason?).
1
u/shumplee Dec 04 '14
python3. Would appreciate some style pointers, just starting out with this lang
1
u/curtmack Dec 04 '14
Clojure:
1
u/[deleted] Dec 04 '14
One of my first programs in C++, what do you think?
1
u/cooper6581 Dec 05 '14
Erlang (no bonus):
1
u/shake_wit_dem_fries Dec 05 '14
Nimrod, with bonus. Strips all punctuation and numbers too.
First Nimrod program, it was pretty enjoyable. It's like C and Python had a compiled love-child. Everything was where you would expect it to be, but it's definitely still in beta.
Code:
1
u/F41LUR3 Dec 05 '14 edited Dec 06 '14
Dart Example: (edited, modified the regex and updated for better error handling completeness, thanks to the folks on freenode in #dart)
The regex will grab words minus punctuation, supports hyphenated words and apostrophes (and any mix therein). URLs will be broken up by periods, but URLs aren't technically words so... :3
Output: http://pastebin.com/NaxpzAF6
1
u/[deleted] Dec 06 '14 edited Dec 06 '14
Perl 6.
It's rather code golfy in the nature (it's Perl 6, what you expected?). Anyway,
slurpreads the file either from argument in ARGV, or from STDIN.lclowercases the read string. Then,.combmatches all words by regex (containing either letters, or a dash).Bagmethod constructs aBagobject which counts how many times each element was specified. Then, withsay, the result is output.1
u/[deleted] Dec 07 '14 edited Dec 07 '14
Here's my C# solution. Feedback appreciated:
1
u/jmac321 Dec 08 '14
first ever swift program
1
u/takishan Dec 10 '14
I did it in python 3. Feedback would be greatly appreciated.
1
u/bob13bob Dec 10 '14 edited Dec 10 '14
Output sample
1
u/kuduwudu Dec 10 '14 edited Dec 12 '14
I know, this is horrible. I need advice please.
Java
1
u/[deleted] Dec 11 '14 edited Dec 11 '14
in Python2. feedback would be greatly appreciated.
1
u/jerro39 Dec 14 '14 edited Dec 14 '14
Mathematica 10.0:
This function also returns a best guess for the number of parts of speech used (although for those where there are more than one option it just returns uncertain). Not surprisingly, this tends to happen a lot. result:
I'm almost surprised that Mathematica doesn't have any major texts built-in given the plethora of information from other subjects that Wolfram has made available.
1
u/[deleted] Dec 15 '14
Python 2.7:
Not the cleanest code but it doesn't need any modules but what's outputed is clean looking (it print's the top 10 words)
1
u/Vyse007 Dec 18 '14
My solution in Python 2.7. Not sure if the output generated is correct, or if it's even the correct approach. Any criticisms welcome, as always.
1
u/asymtex Dec 19 '14
Python 3. Any comments welcome!
1
u/gleventhal Dec 19 '14 edited Dec 19 '14
1
u/atcrd Dec 22 '14
Written in Java.
1
u/5900 Dec 22 '14
perl
1
u/datgohan Dec 25 '14
In Python. Keep trying to think of a good way to sort this and say print the top 10 but struggling.
1
u/Quel Jan 01 '15
Late to the game, but here is this one in R:
With the output:
1
u/Burnz69 Jan 01 '15
Java. Lacks a lot of tuning, but does most of the job, and almost no regex required.
1
u/KnitYourOwnSpaceship Jan 02 '15
1
u/Coneicus Jan 04 '15
Python
Easy one as I already coded something similar in a previous exercise.
1
u/[deleted] Jan 05 '15
This javascript solution requires NodeJS. It's synchronous:
1
u/PapaJohnX Jan 06 '15
Python 3
1
u/zuppy321 Jan 13 '15
Hey everyone,
This will be my first post here. I have been learning Java for 1 month and decided to take on some of these challenges. It would great if people can offer feedback despite it being late.
Classes and Methods
I know there are probably more efficient way, but this is the method I came up with using the limited resources I have.
1
u/voiceoverr Jan 15 '15
Python
This was a good challenge. Would appreciate any feedback on readability or possible reductions!
1
u/HerbyHoover May 16 '15
Perl:
1
u/Steve132 0 1 Dec 01 '14
python
C++11
1
u/patetico Dec 01 '14
Python 3
output:
1
u/ICanCountTo0b1010 Dec 01 '14
Here's a simple python3 script to determine all of the words in a text file. This part doesn't include the output formatting but that's the least interesting part.
0
u/[deleted] Dec 01 '14
[deleted] — view deleted comment
0
u/[deleted] Dec 03 '14
[deleted] — view deleted comment
2
u/[deleted] Dec 02 '14 edited Dec 02 '14
[removed] — view removed comment