本内容仅供笔者自己学习用,内容是将他人的加以整理或总结或日后可能还需要在学习的,本文并非笔者原创,在此声明。
java 代码:
st;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import Matcher;
import Pattern;import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.ption.BadHanyuPinyinOutputFormatCombination;public class Test {//源文件与目标文件的全路径名 private static final String READ_FILE="E:/";private static final String WRITE_FILE="E:/";private static HanyuPinyinOutputFormat speilFormat = new HanyuPinyinOutputFormat();private static BufferedWriter writer = null;private static BufferedReader reader = null;//初始化信息 public static void init()throws IOException{writer = new BufferedWriter(new FileWriter(new File(WRITE_FILE), false));reader = new BufferedReader(new FileReader(new File(READ_FILE)));speilFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);speilFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);speilFormat.setVCharType(HanyuPinyinVCharType.WITH_V);}// 判断字符串是否包含有中文 public static boolean isChinese(String str){String regex = "[\u4e00-\u9fa5]";Pattern pattern = Patternpile(regex);Matcher matcher = pattern.matcher(str);return matcher.find();}//将汉字转换为拼音 public static String chineseToSpell(String chineseStr) throws BadHanyuPinyinOutputFormatCombination{HanyuPinyinString(chineseStr, speilFormat, "");}//将转换后的字符串写入目标文件public static void writeToFile(String spellStr)throws IOException{writer.write(spellStr);}//从源文件读取按行数据 public static void readFromFile()throws IOException, BadHanyuPinyinOutputFormatCombination{String line = null;while((lineadLine())!=null){line = im();//是中文 if(isChinese(line)){line = chineseToSpell(line);}writeToFile(line+"n");}}//关闭文件流 public static void destroy()throws IOException{reader.close();writer.close();}public static void main(String[] args)throws IOException, BadHanyuPinyinOutputFormatCombination{init();readFromFile();destroy();}
}
最后还要加入拼音的jar包,本人用的是pinyin4j-2.5.0.jar包。
本文发布于:2024-02-03 22:39:41,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170697132551482.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |