温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中怎么实现一个英文翻译程序

发布时间:2021-08-07 14:59:41 来源:亿速云 阅读:249 作者:Leah 栏目:编程语言

这期内容当中小编将会给大家带来有关java中怎么实现一个英文翻译程序,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

①FileLoader类

/*文件载入类,将源文件中的内容输出到字节数组中*/package zhidao3_2;import java.io.FileInputStream;import java.io.File;public class FileLoad { public static byte[] getContent(String fileName)throws Exception{ File file = new File(fileName); if(!file.exists()){  System.out.println("输入有误,该文件不存在"); } FileInputStream fis = new FileInputStream(file); int length = (int)file.length(); byte[] data = new byte[length]; fis.read(data); fis.close(); return data; }}

②TxtTrans类

/*文件翻译,将字节数组变为字符串,分离出其中的单词,然后翻译为对应的汉字,去掉空格,变为字符串*/package zhidao3_2;import java.util.StringTokenizer;import java.util.Properties;import java.io.*;public class TxtTrans { private Properties pps; public TxtTrans(){ loadCiku(); } public void loadCiku(){ pps = new Properties(); try{  FileReader fis = new FileReader("g:/ciku.txt");//以字符载入时没有乱码,以字节载入时出现了乱码  pps.load(fis);  fis.close(); }catch(Exception ex){  ex.printStackTrace(System.out);  System.out.println("载入词库时出错"); } //System.out.println(pps.get("china")) ;  } public String trans(byte[] data){ String srcTxt = new String(data); String dstTxt = srcTxt;  String delim = " ,.!\n\t"; //分隔符可以指定 StringTokenizer st = new StringTokenizer(srcTxt,delim,false); String sub,lowerSub,newSub; //int i=0; while(st.hasMoreTokens()){  sub = st.nextToken(); //分割出的一个个单词   lowerSub = sub.toLowerCase();//统一转换为小写,这样可以简化词库  //System.out.println(sub);  newSub = pps.getProperty(lowerSub);  if(newSub != null){ //如果找到了匹配的汉字,则进行替换  dstTxt = dstTxt.replaceFirst(sub, newSub); //只替换第一个,即只替换了当前的字符串,否则容易造成ch我na的例子  //System.out.println(dstTxt);  } }  return dstTxt.replaceAll(" ", ""); //去掉空格 }   }

③FileOutput类

/*将字符串输出到文件*/package zhidao3_2;import java.io.File;import java.io.FileOutputStream;public class FileOutput { public static void output(String text,String fileName)throws Exception{ File file = new File(fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(text.getBytes()); fos.close(); }}

④主函数

package zhidao3_2;import javax.swing.JOptionPane;public class Main {  public static void main(String[] args) { String srcFile = JOptionPane.showInputDialog("输入源文件"); try{  byte[] data = FileLoad.getContent(srcFile);  TxtTrans tt = new TxtTrans();  String dString = tt.trans(data);  FileOutput.output(dString, "g:/result.txt"); }catch(Exception ex){  JOptionPane.showMessageDialog(null, "操作异常");  System.exit(1); }   JOptionPane.showMessageDialog(null, "翻译完毕"); } }

上述就是小编为大家分享的java中怎么实现一个英文翻译程序了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI