提取文本中的汉字字符串

提取文本中的汉字字符串

代码中含有中文字符,希望将代码中的中文字符提取出来,输出到数据库表格,然后补充对应的英文翻译。
继续处理代码,将文中的中文字符,通过查找数据库,替换成英文。
本文关键的地方,在于汉字字符串的提取,将连续的汉字,识别为一个字符串。

   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;
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值