We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Counting Words in a String
Page Index Toggle Pages: 1
Counting Words in a String (Read 921 times)
Counting Words in a String
Jan 15th, 2008, 5:37am
 
so i found this great code that parses through a text file and counts the amount of times all the words show up.

i'm trying to modify the code so that it allows me to just get the value of certains words.

like
happy:1
sad:4

so that i can extract those int values as variables.

here's the code


String lines[];
String list[];

void setup() {
lines = loadStrings("http://api.wefeelfine.org:8080/ShowFeelings?display=text&returnfields=feeling,conditions&limit=50");
println("there are" + lines.length + "lines");

Words words = new Words();

for (int i=0; i < lines.length; i++) {
String list[] = splitTokens(lines[i]);
for (int j=0; j < list.length; j++) {
words.addWord(list[j]);
}
}
words.printWords();
}


class Words {

Hashtable ht=new Hashtable();

void addWord(String txt) {
Word word;
if (ht.containsKey(txt)) {
word = (Word)ht.get(txt);
word.count++;
} else {
word = new Word(txt);
}
ht.put(txt,word);
}

void printWords() {
for (Enumeration e = ht.keys() ; e.hasMoreElements() Wink {
String name = e.nextElement().toString();
Word word = (Word)ht.get(name);
println(word.txt + ":" + word.count);
}
}
}

class Word {

public String txt;
public int count = 1;

Word(String txt) {
this.txt = txt;
}
}


Re: Counting Words in a String
Reply #1 - Oct 24th, 2009, 6:23am
 
Hi! I'm trying to visulize song lyrics with ellipses. I got close now, thanks to your code and with external help.
Now I can represent the lyrics of only one song. If I want to have more than only one .txt file loaded and represented have you any suggestion on how managing it?
At first I thought to create a class Word for each file, but I quickly realized that I coudn't, at least with my little experience in Processing.
Thanks a lot,

Best
Re: Counting Words in a String
Reply #2 - Oct 24th, 2009, 6:59am
 
Well, a quite natural extension of the Words class is to add a parse() method: you create a Words instance per file, using the URL / path as constructor parameter. Then you can ask to parse() (or just do that in the constructor).
Page Index Toggle Pages: 1