Skip to content

Instantly share code, notes, and snippets.

@alexandre
Last active August 29, 2015 14:08
Show Gist options
  • Save alexandre/f03f98a8e5ba9fddd0be to your computer and use it in GitHub Desktop.
Save alexandre/f03f98a8e5ba9fddd0be to your computer and use it in GitHub Desktop.
word counter
from itertools import groupby
def word_counter(*words):
'''Write a Python program that inputs a list of words, separated by white-
space, and outputs how many times each word appears in the list.
'''
return {word: len(list(word_group)) for word, word_group in
groupby(sorted(words), key=lambda x: x)}
@pbalduino
Copy link

Clojure:

(def frase "vaca batata galinha batata coxinha macaco batata vaca batata")

(defn word-counter 
  "Write a Clojure program that inputs a list of words, 
   separated by white-space, and outputs how many times
   each word appears in the list."
  [text]
  (sort-by last (frequencies (clojure.string/split frase #" "))))

(word-counter frase)
; (["galinha" 1] ["coxinha" 1] ["macaco" 1] ["vaca" 2] ["batata" 4])

@samuelgrigolato
Copy link

Java:

package wordcount;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        String phrase = "vaca batata galinha batata coxinha macaco batata vaca batata";
        Map<String, Integer> words = new TreeMap<>(); // usei o TreeMap para ordenar a resposta
        for (String word : phrase.split(" ")) {
            int freq = words.containsKey(word) ? words.get(word) : 0;
            words.put(word, freq + 1);
        }
        for (Entry<String, Integer> word : words.entrySet())
            System.out.println(word.getKey() + " (" + word.getValue() + ")");
    }
}

Java 8 (utilizando streams e a API revisada da interface Map):

package wordcounter;

import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {

        String phrase = "vaca batata galinha batata coxinha macaco batata vaca batata";
        Map<String, Integer> words = new TreeMap<>(); // usei o TreeMap para ordenar a resposta

        Arrays.stream(phrase.split(" "))
            .forEach((word) -> words.merge(word, 1, (existente, novo) -> existente + novo));

        words.entrySet().stream()
            .map((entry) -> entry.getKey() + " (" + entry.getValue() + ")")
            .forEach(System.out::println);

    }
}

@afonso
Copy link

afonso commented Nov 3, 2014

Ruby:

palavras = "Garoa Hacker & Hacker * Clube $"
puts palavras.downcase.scan(/\w+/).each_with_object(Hash.new(0)) { |palavra, hash| hash[palavra] += 1 }
#{"garoa"=>1, "hacker"=>2, "clube"=>1}

@myhro
Copy link

myhro commented Nov 3, 2014

#!/bin/bash

FRASE=$(echo "vaca batata galinha batata coxinha macaco batata vaca batata" | sed 's/ /\n/g')
PALAVRAS=$(echo "$FRASE" | sort | uniq)
for w in $PALAVRAS; do
    echo $w $(echo "$FRASE" | grep -c $w)
done
batata 4
coxinha 1
galinha 1
macaco 1
vaca 2

@alexandre
Copy link
Author

by Felix Schneider.

Lua:

-- word stat
word_stat = function (words)
    local tbl = {}
    for match in words:gmatch("%w+") do
        tbl[match] = (tbl[match] or 0) + 1;
    end
    return tbl;
end

-- testing...
-- test = "hallo hallo hoho hallo hoho haha haha hallo hoho"
-- for k, v in pairs(word_stat(test)) do print(k, v) end

@alexandre
Copy link
Author

by @firebits

GoLang:

package main

import (
    "fmt"
    "strings"
)

func ContadorPalavras(s string) map[string]int {
    strs := strings.Fields(s)
    res := make(map[string]int)

    for _, str := range strs {
        res[strings.ToLower(str)]++
    }
    return res
}

func main() {
    fmt.Println(ContadorPalavras("Contador de Palavras em Golang"))
    fmt.Println(ContadorPalavras("Golang GOLANG gOlAnG goLANG"))
}

@bitmaybewise
Copy link

Haskell:

import Data.List

frase = "vaca batata galinha batata coxinha macaco batata vaca batata"

wordCounter frase = 
    nub $ map (\x -> (x, length $ filter (== x) palavras)) palavras
    where palavras = words frase

-- [("vaca",2),("batata",4),("galinha",1),("coxinha",1),("macaco",1)]

https://gist.github.com/hlmerscher/59ab5328344a466a0f6d

@nuit
Copy link

nuit commented Nov 4, 2014

Lisp L-99:

(defun encode-modified (list)
  (let ((result    '())
        (count     0)
        (last-item nil))
    (labels ((collect-result ()
               (push (if (= 1 count)
                         last-item
                         (list count last-item))
                     result))
             (new-item (item)
               (setf count 1
                     last-item item))
             (same-item ()
               (incf count))
             (return-result ()
               (when (plusp count)
                 (collect-result))
               (nreverse result)))
      (dolist (item list  (return-result))
        (cond
          ((zerop count)        (new-item item))
          ((eql item last-item) (same-item))
          (t                    (collect-result)
                                (new-item item)))))))
(princ (encode-modified '(galinha coxinha macaco vaca vaca batata batata batata batata)))

(GALINHA COXINHA MACACO (2 VACA) (4 BATATA))

@efficens
Copy link

efficens commented Nov 4, 2014

using System;
using System.Linq;
using System.Collections.Generic;

namespace WordCount
{
    class Program
    {
        public static void Main(string[] args)
        {
             String phrase = "vaca batata galinha batata coxinha macaco batata vaca batata";

             List<String> words = phrase.Split ( ' ' ).ToList ();

             foreach ( var group in words.GroupBy ( p => p ) )
                Console.WriteLine ( "{0} - {1}", group.Key, group.Count ());
        }
    }
}

@Eldius
Copy link

Eldius commented Nov 4, 2014

Groovy:

def wordCount(text) {
    def map = [:]
    def words = text.split(" ")
    words.each() { word -> 
        map.putAt(word, map.get(word, 0) + 1)
    }
    map
}

def text = "vaca batata galinha batata coxinha macaco batata vaca batata"

def map = wordCount(text)

map.each { key, value -> println """${key}: ${value} """ }

@danilobellini
Copy link

Shell script, using arguments:

#!/bin/sh
echo $@ | tr ' ' '\n' | sort | uniq -c

e.g.:

./wordcounter.sh vaca batata galinha batata coxinha macaco batata vaca batata

http://pastebin.com/ZTdJcKC8

@NicolasFrancaX
Copy link

Javascript:

function word_counter(words) {
  var counter = {};

  words.split(' ').map(function(word) {
    !counter[word] ? counter[word] = 1 : counter[word] += 1;
  });

  return counter;
}

var frase = 'vaca batata galinha batata coxinha macaco batata vaca batata';

word_counter(frase); 
// => Object {vaca: 2, batata: 4, galinha: 1, coxinha: 1, macaco: 1}

@Eldius
Copy link

Eldius commented Nov 10, 2014

Scala

object Test extends App{

  def count(text: String): Map[String, Int] = {
    def count(words: Array[String]): Map[String, Int] = {
      if(words.size == 1) {
        return Map(words.head -> 1)
      } else {
        val map = count(words.tail)
        return map + (words.head -> (map.getOrElse(words.head, 0) + 1))
      }
    }
    return count(text.split(" "))
  }

  println(count("vaca batata galinha batata coxinha macaco batata vaca batata"))
}

@alexandre
Copy link
Author

Outra versão em python....:

def word_counter(string):
    return {x: string.count(x) for x in string.split()}

@alexandre
Copy link
Author

Outra versão ainda mais simples:

import collections


def word_counter(*string):
    return dict(collections.Counter(string).items())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment