JAVA 中文分词
- 格式:pdf
- 大小:215.68 KB
- 文档页数:4
//输出TreeMap的values,即分拆好的句子
System.out.println(tm.values()); }
}
中文词库文件 chinese_word.txt 昨天,星期一,我,今天,你,在,上午,个,餐厅,一顿,一,下午,部,去,晚上,他,苹果手机, 她,中午,的,买,吃饭,了,电脑,买了,在,吃,两,饭,手机,顿,吃了 (逗号为英语状态) 理论上,中文词库越详细,词条越多,分词越准确。就像表达吃饭这个意思,其 实可以包含 吃饭, 吃, 饭, 吃了, 了, 一顿, 一, 顿, 等词语。
package collection_package;
import java.util.*;
public class TestAnalysis { public static void main(String[] ary) { StringAnalysis sa = new StringAnalysis(); InsertString is = new InsertString(); is.gettext(); // System.out.println(is.s); sa.get(); String sretain; sretain = sa.sen;
import java.io.*; import java.util.*;
public class InsertString {
public static String s = new String();
public void gettext() { try { //从电脑文件夹读入‘中文词库’文件 BufferedReader input = new BufferedReader(new
JAVA 中文分词实现
中文分词,用java实现,算法主要思想是正向最大匹配。利用ArryList存放中文
分词库中的词语,要按词语长度存放,先存放四字词语,最后存放单个字。然后
将输入的语句与ArryList逐一对比词语,匹配。最后将匹配好的分词放入
TreeMap,重新按原来顺序排好,输出。
package collection_package;
// 读入语句,读取要分析的句子
Scanner scanner = new Scanner(System.in); sen = scanner.nextLine(); }
public String compare(String str, ArrayList<String> list, int n) { String stemp; String strre; String strresult;
}
package collection_package;
import java.util.*;
public class StringAnalysis { public static String sen; public ArrayList al = new ArrayList();
public void get() { System.out.println("Please input the sentence");
FileReader("./chinese_word.txt")); s = input.readLine(); input.close();
} catch (Exception e) { System.out.println("Read Fail");
} }
//将词库放入ArrayList,按词语长度放置,通常词语最长为4,最为1 public ArrayList split(String str, int l) { String[] strarray = str.split(","); ArrayList al = new ArrayList(); for (int i = 0; i < strarray.length; i++) { if (strarray[i].length() == l) // al.add(strarray[i]); } return al; }
大家可以自己扩充中文词库文件。
截图
TreeMap tm = new TreeMap(); Iterator it = sa.al.iterator(); while (it.hasNext()) {
String s = (String) it.next();
tm.put(sa.sen.indexOf(s), s); //将匹配了的ArrayList放入TreeMap
//将词库放入ArrayList,按词语长度放置,通常词语最长为4,最短长度为1
for (int i = 4; i > 0; i--) sretain = pare(sretain, is.split(is.s, i), i);
// System.out.println(sa.al);
//新建一个TreeMap,为了可以使匹配了的分词重新按原先的顺序排列பைடு நூலகம்
}
strre = al.toString();
//删去已经匹配的词语
strre = strre.replace(" ", ""); strre = strre.replace(",", "|"); strre = strre.substring(1, strre.length() - 1); // System.out.println(strre); strresult = str.replaceAll(strre, ""); // System.out.println(strresult); return strresult; } }
//将句子与ArrayList对比,匹配的add进另一个ArrayList
for (int i = 0; i < str.length() - n + 1; i++) { stemp = str.substring(i, i + n); if (list.contains(stemp)) al.add(stemp);