java 编程点滴
提取文本中的汉字字符串
代码中含有中文字符,希望将代码中的中文字符提取出来,输出到数据库表格,然后补充对应的英文翻译。
继续处理代码,将文中的中文字符,通过查找数据库,替换成英文。
本文关键的地方,在于汉字字符串的提取,将连续的汉字,识别为一个字符串。
public void fileCnToEn( String filePath) throws IOException {
StringBuffer buffer=new StringBuffer();
InputStream is = new FileInputStream(filePath);
String line; // 用来保存每行读取的内容
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
line = reader.readLine(); // 读取第一行
while (line != null) { // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append("\n"); // 添加换行符
line = reader.readLine(); // 读取下一行
}
reader.close();
is.close();
String ftxt=buffer.toString();
List<String> cnLst=getCnStrLst(ftxt); //从文本内容中,提取汉字字符串
for(String tmp:cnLst){
CnDicPO tmpPo=cnDicDAO.selectByPrimaryKey(tmp); //以汉字字符串查数据库
if(StringUtils.isNotBlank(tmpPo.getEn())){
ftxt=ftxt.replace(tmp, tmpPo.getEn());
}
}
FileWriter writer;
try {
writer = new FileWriter(filePath);
//write.write("");//清空原文件内容
writer.write(ftxt);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//从文本内容中,提取汉字字符串,返回一个汉字字符串列表
List<String> getCnStrLst(String text){
String regex="[\\u4e00-\\u9fa5]";
List<String> cnStr=new ArrayList<String>();
Matcher matcher = Pattern.compile(regex).matcher(text);
int lastPos=0;
String packStr="";
while (matcher.find()) {
if(matcher.end()==(lastPos+1)){
packStr=packStr+matcher.group(0); //拼接连续的汉字,形成汉字字符串
}else{
boolean find=false;
for(String tmp:cnStr){
if(tmp.equals(packStr)){
find=true;
break;
}
}
if(find==false && StringUtils.isNotBlank(packStr)){
cnStr.add(packStr); //汉字字符串插入列表中
}
//新的字符串开始
packStr=matcher.group(0);
}
lastPos=matcher.end();
}
for(String tmp:cnStr){
CnDicPO tmpPo=cnDicDAO.selectByPrimaryKey(tmp); //数据库操作
if(tmpPo == null){
CnDicPO record=new CnDicPO();
record.setCn(tmp);
cnDicDAO.insertSelective(record);
}
}
return cnStr;
}