yangfanconan 发表于 2013-5-9 20:27:40

Processing之旅-----【7课,HashMap实验课】

同学们大家好,我们上课。这节课依然是数据结构的实验课。
/**
* HashMap例子
* by Daniel Shiffman.
*
* 这个例子说明了并示范了如何使用 HashMap 去存储
* 一个对象的集合,并用一个键值去检索. 这看起来非常像数组,
* 只有代替访问元素的数字索引, 我们用一个字符串
* 如果熟悉其他语言中的关联数组,
* 这是同样的概念。
*
* 这个例子使用哈希映射了一个简单的集合
* http://en.wikipedia.org/wiki/Concordance_(publishing)
*/

// The next line is needed if running in JavaScript Mode with Processing.js
/* @pjs font="Georgia.ttf"; */

HashMap<String, Word> words;// HashMap 对象

String[] tokens;// 从输入文件的所有单词的数组
int counter;//计数器

void setup() {
size(640, 360);//设置窗口大小

words = new HashMap<String,Word>();//对HashMap对象进行初始化操作

// 读取文件并分割
String[] lines = loadStrings("dracula.txt");
String allText = join(lines, " ");//这句话的意思相当于allText=allText+lines+" ";
tokens = splitTokens(allText, " ,.?!:;[]-");//去掉alltext中的,.?!:;[]-符号并把新的字符串返回给tokens

// 创建字体
textFont(createFont("Georgia", 24));
}

void draw() {
background(51);
fill(255);

// 一次传送一个词
String s = tokens;
counter = (counter + 1) % tokens.length;

// 这个词是否在HashMap中
if (words.containsKey(s)) {
    // 得到这个词的对象并增加计数器
    // 我们通过键值访问HashMap中的对象, String
    Word w = words.get(s);
    w.count();
} else {
    // 否则做一个新的词在HashMap中
    Word w = new Word(s);
    // 添加元素到HashMap 用put()函数 有两个 两个参数, "key" and "value"
    // 这个key对于我们来说就是String, the value 就是 Word 对象
    words.put(s, w);   
}

// x and y 将被用找出每一个单词
float x = 0;
float y = height-10;

// 查看每一个单词
for (Word w : words.values()) {
   
    // 每个单词只显示3次
    if (w.count > 3) {
      // 这个size就是count
      int fsize = constrain(w.count, 0, 100);
      textSize(fsize);
      text(w.word, x, y);
      // 在X轴上移动
      x += textWidth(w.word + " ");
    }
   
    //如果X上移动到边缘了,就移动Y轴
    if (x > width) {
      x = 0;
      y -= 100;
      // 如果y轴也移动满了我们就停止移动
      if (y < 0) {
      break;
      }
    }
}
}

class Word {

int count;
String word;

Word(String s) {
    word = s;
    count = 1;
}

void count() {
    count++;
}

}//



效果如图,非常明显,就是单词出现的次数越多就变得越大。
好了,同学们下课。

弘毅 发表于 2013-5-10 10:54:16

这个效果好~~~

yangfanconan 发表于 2013-5-10 17:10:47

弘毅 发表于 2013-5-10 10:54 static/image/common/back.gif
这个效果好~~~

谢谢支持~:lol其实我也在群里啊~两个群都有,咱们Processing区为什么没有像Arduino一样的精华置顶设置啊?:lol

弘毅 发表于 2013-5-10 17:21:56

yangfanconan 发表于 2013-5-10 17:10 static/image/common/back.gif
谢谢支持~其实我也在群里啊~两个群都有,咱们Processing区为什么没有像Arduino一样的精华置顶设置啊? ...

:lol偶把你权限加为斑竹了。。。这样你就有权限了。。

yangfanconan 发表于 2013-5-10 17:38:13

弘毅 发表于 2013-5-10 17:21 static/image/common/back.gif
偶把你权限加为斑竹了。。。这样你就有权限了。。

谢谢~嘿嘿:lol

迷你强 发表于 2013-5-10 21:47:31

好强大。。好给力。。。

LINK~ 发表于 2014-10-30 16:11:32

The file "dracula.txt" is missing or inaccessible, make sure the URL is valid or that the file has been added to your sketch and is readable.这个例子也出现错误了:):)

LINK~ 发表于 2014-10-30 16:16:31

dracula.txt这个文件放在哪里啊

Qiu_SaMa 发表于 2017-6-2 13:30:49

LINK~ 发表于 2014-10-30 16:16
dracula.txt这个文件放在哪里啊

放到和你创建的.pde格式的代码文件夹下就行。
页: [1]
查看完整版本: Processing之旅-----【7课,HashMap实验课】