package com.zzsn.generation.test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
* ver: 2013.09.20
**/
public class TokenTf {

	/**
	 * 保存tf值
	 */
	public double tf;

	/**
	 * 保存某一篇文档的所有词组
	 */
	private HashMap hm = null;

	/**
	 * hm的大小
	 */
	private int hmsize;

	/**
	 * hm的迭代器
	 */
	private Iterator hmitor = null;

	/**
	 * 构造方法，初始化hm
	 */
	public TokenTf() {
		//if (hm == null) {
			hm = new HashMap();
			hmitor = null;
		//}
	}

	/**
	 * 重新初始化hm
	 */
	public void setHashMapToNull() {
		this.hm = new HashMap();
	}

	/**
	 * 返回hmitor迭代器
	 * 
	 * @return
	 */
	public Iterator returnHmitor() {
		return this.hmitor;
	}

	public void InitHmitor()
	{
		this.hmitor = null;
	}
	
	/**
	 * 将这一篇文档的所有词组加入到hm中
	 * 
	 * @param s
	 */
	public void formhm(String s) {
		//
		int num = 0;
		Object freq_obj = new Object();
		// 如果包含
		if (hm.containsKey(s)) {
			freq_obj = hm.get(s);
			num = Integer.parseInt(freq_obj.toString());
			// 出现次数加１
			num++;
			// 重新写入hm
			hm.put(s, new Integer(num));
		} else {
			hm.put(s, new Integer(1));
		}
	}

	/**
	 * 计算字符串s的tf值
	 * 
	 * @param s
	 */
	public double countTf(String s) {
		if (hmsize == 0)
			hmsize = hm.size();
		int stringnum = 0;

		if (!hm.containsKey(s))
			tf = 0.0;
		else {
			stringnum = Integer.parseInt(hm.get(s).toString());
			tf = stringnum / (double) hmsize;
		}
		return tf;
	}

	public int getTF(String s) {
		if (!hm.containsKey(s))
			return 0;
		else {
			int stringnum = Integer.parseInt(hm.get(s).toString());
			return stringnum;
		}

	}

	/**
	 * 打印该篇文档的所有词组的tf值
	 */
	public void printAllTf() {
		hmsize = hm.size();
		if (hm == null)
			System.out.println("null");
		else {
			Set set = hm.entrySet();
			hmitor = set.iterator();
			while (hmitor.hasNext()) {
				Map.Entry entry = (Map.Entry) hmitor.next();
				Object key = entry.getKey();
				Integer value = (Integer) entry.getValue();
				// System.out.println(key.toString()+" "+value.intValue()/(double)hmsize);
			}
		}
		hmitor = null;
	}

	/**
	 * 切一个文本时取得下一个切出来的字符串
	 * 
	 * @return
	 */
	public String next() {
		if (hmitor == null) {
			Set set = hm.entrySet();
			hmitor = set.iterator();
		}
		while (hmitor.hasNext()) {
			Map.Entry entry = (Map.Entry) hmitor.next();
			Object key = entry.getKey();
			return key.toString();
		}
		return null;
	}

	public HashMap gethm() {
		return this.hm;
	}
}
