这是我们做的一个小作业,不多说
直接附上我写的代码:
public void Zheng() { try { BufferedReader bre = null; //String file = "d.txt"; String file = "Dict.txt"; bre = new BufferedReader(new FileReader(file)); String line; try { while ((line = bre.readLine()) != null) // 判断最后一行不存在,为空结束循环 { temp.add(line); // System.out.println(line);// 原样输出读到的内容 } bre.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { System.out.println("未成功读取文件"); e.printStackTrace(); } String sub_str; while (start < total_len) { boolean flag = false; tmp_len = start + max_len <= total_len ? max_len : total_len - start; label: while (tmp_len > 0) { // System.out.println(1); sub_str = receive.substring(start, start + tmp_len); // System.out.println(sub_str); for (i = 0; i < temp.size(); i++) { if (sub_str.equals(temp.get(i))) { flag = true; } } if (flag == true) { words.add(receive.substring(start, start + tmp_len)); start = start + tmp_len; break label; } else { tmp_len = tmp_len - 1; // System.out.println(tmp_len); } /* * if sub_str in dict: words.append(setence[start : start + * tmp_len]) start = start + tmp_len break else: tmp_len = * tmp_len -1 */ } if (tmp_len == 0) { words.add(receive.substring(start, start + 1)); start = start + 1; } }
效果就是按照词库中的词将一段语句分割开来。
附上词库的位置:
https://pan.baidu.com/s/1pLBKer5