ITeye博客

服务版翻译

抛出异常的爱 · 2008-11-13 11:16 · 技术 · Markdown

前阵子写了个用google翻译的html版 看了http://dennis-zane.iteye.com/blog/57533 的博客去找了那个java版 的 了解了下原理 但他的代码不好用.

只好自己写了个

    public   static   void  main(String[] args)  throws  Exception {
    	  String theword = "my god ";
    	  String urlstr = engineUrl + "?text=" + theword + "&langpair=" + LANGPAIR_EN_CN;
    	  HttpClient client = new HttpClient();
    	  client.getHostConfiguration().setHost("translate.google.com",80,"http");
    	  
    	 
    	  PostMethod post = new PostMethod("/translate_t");
    	  NameValuePair f01 = new NameValuePair("text",theword);
    	  NameValuePair f02 = new NameValuePair("langpair",LANGPAIR_EN_CN);
    	  post.setRequestBody(new NameValuePair[]{f01,f02});
    	  int scode = client.executeMethod(post);
    	  System.out.println(post.getURI());
    	  String result = post.getResponseBodyAsString();
    	  

    	  post.releaseConnection();
//    	  System.out.println(result);

//    	  String result = "<div id=result_box dir=\"ltr\"> aaa </div> ";
    	  Pattern p = Pattern.compile("<div id=result_box(.*?)>(.*?)</div>"); 
    	  Matcher m = p.matcher(result);
    	  //System.out.println(m.find());
    	 while(m.find()){
    		 System.out.println(m.group(2));
    	 }
     }

原理测试完了 正在重构ing

评论(9)

  1. #9 楼 · lzj0470 · 2008-12-22 09:16

    呵呵,到目前为止,我看错了字,我以为你说写完在发给我,原来是我写,这几天都在忙什么国外网站一些东西,有空再写写,写完给你一份,谢谢提供思路。

  2. #8 楼 · lzj0470 · 2008-12-18 17:41

    好的,先谢谢,期待中~~~

  3. #7 楼 · 抛出异常的爱 · 2008-12-18 13:41

    lzj0470 writes:

    呵呵,你加一个线程睡眠是可以解决问题的。但是还是不能到达俺的要求,不过没办法,俺不能处理图像识别技术。目前我是想通过多个翻译工具进行翻译,或许也可以解决你那部分空闲的时间。

    那就要写一个代理了.... 一个线程用一个代理..... 写好了发我一份.借鉴一下.

  4. #6 楼 · lzj0470 · 2008-12-18 09:59

    呵呵,你加一个线程睡眠是可以解决问题的。但是还是不能到达俺的要求,不过没办法,俺不能处理图像识别技术。目前我是想通过多个翻译工具进行翻译,或许也可以解决你那部分空闲的时间。

  5. #5 楼 · 抛出异常的爱 · 2008-12-17 20:34

    lzj0470 writes:

    我几天也弄了一个在线翻译,但是遇到了一个问题,如果你的程序频繁的访问它的话,它会给你出一道难题,就是关于验证码的问题,只要你处理要验证码的问题之后,才能登陆它的翻译系统进行翻译,不知道你有没有考虑过这个问题。

             while(it.hasNext()){  
                 tmp =it.next();  
                 buffer.append(tmp+"|");  
                 buffer.append(translateE2C(tmp)+"\n");  
                 buffer.append("\n");  
     //          Thread.currentThread().sleep(5*1000);     
             }  
    

    看到注掉的那行没有? 对的,他就是为了防止被人挡住的.. 必竟作人不能太无耻吧.... 后来我发现注掉也没问题. 看来google还是很大方的.

  6. #4 楼 · bubble · 2008-12-16 09:52

    呵呵,我没看明白你想做什么,给Google的Translate API封装一下? 那个断句的是做什么的啊,想对一篇文章自己断句,然后再每句用Google自动翻译? 关于断句可以参考一下LISA的SRX,网上应该有些总结的片段切割交换规则集。 还有就是Google的Translate API短句可读性还凑合,长句基本不可读,所以比较怀疑你的做法。 我看你的代码好像文件是纯文本的,对编码问题我遇到的问题是你必须人为告诉程序文件是什么编码的,因为它没有文件头,极度郁闷~,其他文件还好 不知道你做的是什么,辅助翻译之类的话,有空交流一下 :arrow:

  7. #3 楼 · lzj0470 · 2008-12-13 11:01

    我几天也弄了一个在线翻译,但是遇到了一个问题,如果你的程序频繁的访问它的话,它会给你出一道难题,就是关于验证码的问题,只要你处理要验证码的问题之后,才能登陆它的翻译系统进行翻译,不知道你有没有考虑过这个问题。

  8. #2 楼 · 抛出异常的爱 · 2008-11-14 17:20
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    import org.apache.commons.collections.Transformer;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.io.FileUtils;
    
    
    
    
    
    public     class   GoogleTranslationEngine    implements Transformer  {
         String engTxt;
          // 定义互译语言对常数变量,符合google页面相关对译语言对的值
          public   static   final  String LANGPAIR_CN_EN = "zh-CN|en" ; // 汉语到英语
          public   static   final  String LANGPAIR_EN_CN = "en|zh-CN" ; // 英语到汉语
          public   static   final  String LANGPAIR_KO_CN = "ko|zh-CN" ; // 朝鲜语到汉语
          public   static   final  String LANGPAIR_EN_JA = "en|ja" ; // 英语到日语
         
          // 定义编码常数
          public   static   final  String CHARSET_CN = "GBK" ;
          public   static   final  String CHARSET_JA = "Shift_JIS" ;
         
          // google在线翻译引擎url
          static   final  String engineUrl = "http://translate.google.com/translate_t" ; 
    
         public String translateE2C(String theword) throws HttpException, IOException{
       	  HttpClient client = new HttpClient();
    	  client.getHostConfiguration().setHost("translate.google.com",80,"http");
    		  PostMethod post;
    		  post = new PostMethod("/translate_t");
    				  NameValuePair f01 = new NameValuePair("text",theword);
    				  NameValuePair f02 = new NameValuePair("langpair",LANGPAIR_EN_CN);
    		  post.setRequestBody(new NameValuePair[]{f01,f02});
    	  client.executeMethod(post);
    	  String result = post.getResponseBodyAsString();
    	  
    
    	  post.releaseConnection();
    	  Pattern p = Pattern.compile("<div id=result_box(.*?)>(.*?)</div>"); 
    	  Matcher m = p.matcher(result);
    		 if (m.find()){
    			 return m.group(2);
    		 }
        	 return "";
         }
    
         public GoogleTranslationEngine setEngText(String str){
        	 this.engTxt = str;
        	 return this;
         }
         public String getEngText(){
        	 return this.engTxt;
         }
     	public GoogleTranslationEngine formatStringDelEnter() {
    		this.engTxt = this.engTxt.replaceAll("\\n", "");
    		return this;
    	}
    	public GoogleTranslationEngine formatStringAddEnterByPoint() {
    		this.engTxt = this.engTxt.replaceAll("\\.", ".\n");
    		return this;
    	}
    
    	public GoogleTranslationEngine formatStringAddEnterByString(String str){
    		String reg ="\\s["+str.tolowercase().charat(0)+"|"+str.touppercase().charat(0)+"]"+str.substring(1,str.length())+"\\s";
    		this.engTxt = this.getEngText().replaceAll(reg, "\n "+str.toLowerCase()+" ");
    		return this;
    	}
    	@SuppressWarnings("unchecked")
    	public GoogleTranslationEngine formatStringAddEnterByList(){
    		List list = new ArrayList();
    		list.add("and");
    		list.add("or");
    		list.add("but");
    		formatStringAddEnterByPoint();		
    		return formatStringAddEnterByList(list);
    	}
    	@SuppressWarnings("unchecked")
    	public GoogleTranslationEngine formatStringAddEnterByList(List list){
    		Iterator<String > it = list.iterator();
    		while(it.hasNext()){
    			formatStringAddEnterByString(it.next());
    		}
    		return this;
    	}
         @SuppressWarnings("unchecked")
    	public void readFile(String filename) throws IOException, InterruptedException{
        	 this.setEngText(FileUtils.readFileToString( new File(filename),"UTF-8"));
        	 FileUtils.writeStringToFile(new File(filename),this.formatStringAddEnterByList().getEngText() ,"UTF-8");
        	 List list = FileUtils.readLines( new File(filename),"UTF-8");
        	Iterator<String> it  = list.iterator();
        	StringBuffer buffer = new StringBuffer();
        	String tmp;
        	while(it.hasNext()){
        		tmp =it.next();
        		buffer.append(tmp+"|");
        		buffer.append(translateE2C(tmp)+"\n");
        		buffer.append("\n");
    //    		Thread.currentThread().sleep(5*1000);   
        	}
        	FileUtils.writeStringToFile(new File(filename+".zhn"), buffer.toString(), "UTF-8");
         }
          public   static   void  main(String[] args)  throws  Exception {
        	GoogleTranslationEngine e = new GoogleTranslationEngine();
    
    
    
        	 e.readFile("test.eng");
         }
          
    //	private Object translateK2C(String theword) throws HttpException, IOException {
    //	   	  HttpClient client = new HttpClient();
    //		  client.getHostConfiguration().setHost("translate.google.com",80,"http");
    //			  PostMethod post;
    //			  post = new PostMethod("/translate_t");
    //					  NameValuePair f01 = new NameValuePair("text",theword);
    //					  NameValuePair f02 = new NameValuePair("langpair",LANGPAIR_KO_CN);
    //			  post.setRequestBody(new NameValuePair[]{f01,f02});
    //		  client.executeMethod(post);
    //		  String result = post.getResponseBodyAsString();
    //		  
    //
    //		  post.releaseConnection();
    //		  Pattern p = Pattern.compile("<div id=result_box(.*?)>(.*?)</div>"); 
    //		  Matcher m = p.matcher(result);
    //			 if (m.find()){
    //				 return m.group(2);
    //			 }
    //	    	 return "";
    //	}
    	public Object transform(Object obj){
    		try {
    			return translateE2C(obj.toString());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return "";
    		
    	}
    
    
    
    
     } 
    
    
    把断句作了一下
    import static org.junit.Assert.assertEquals;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.commons.io.FileUtils;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.BeforeClass;
    import org.junit.Test;
    
    
    public class GoogleTranslationEngineTest {
    	String filename = "testFormatFile";
    	GoogleTranslationEngine g;
    	@BeforeClass
    	public static void setUpBeforeClass() throws Exception {
    	}
    
    	@Before
    	public void setUp() throws Exception {
    		g = new GoogleTranslationEngine();
    		FileUtils.writeStringToFile(new File(filename), "a\nb\nc", "UTF-8");
    	}
    
    	@After
    	public void tearDown() throws Exception {
    		new File(filename).delete();
    	}
    
    	@Test
    	public void test去掉回车变成一行() throws IOException {
    		String str =FileUtils.readFileToString( new File(filename),"utf-8");
    		assertEquals("a\nb\nc", str);
    		g.setEngText(str);
    		assertEquals("abc",g.formatStringDelEnter().getEngText());
    		
    	}
    	@Test
    	public void test在每个句号后加回车(){
    		 g.setEngText("abc.acd");
    		assertEquals("abc.\nacd", g.formatStringAddEnterByPoint().getEngText());
    		
    	}
    	@SuppressWarnings("unchecked")
    	@Test
    	public void test把字串放入E中用点连接方式格式化(){
    		String str; 
    		List list ;
    		str=g.setEngText("去\n回\n车").formatStringDelEnter().getEngText();
    		assertEquals("去回车", str);
    		str =g.setEngText("对句号.加回车").formatStringAddEnterByPoint().getEngText();
    		assertEquals("对句号.\n加回车", str);
    		list = new ArrayList();
    		list.add("and");
    		str =g.setEngText("对 and 加回车").formatStringAddEnterByList(list).getEngText();
    		assertEquals("对\n and 加回车", str);
    		str =g.setEngText("对 And 加回车").formatStringAddEnterByList(list).getEngText();
    		assertEquals("对\n and 加回车", str);
    		str =g.setEngText("对and连在一起的不加回车").formatStringAddEnterByList(list).getEngText();
    		assertEquals("对and连在一起的不加回车", str);		list = new ArrayList();
    		list.add("Or");
    		str =g.setEngText("对 or 加回车").formatStringAddEnterByList(list).getEngText();
    		assertEquals("对\n or 加回车", str);
    
    		str =g.setEngText("对 任意字串 加回车").formatStringAddEnterByString("任意字串").getEngText();
    		assertEquals("对\n 任意字串 加回车", str);
    		str =g.setEngText("对任意字串 不加回车").formatStringAddEnterByString("任意字串").getEngText();
    		assertEquals("对任意字串 不加回车", str);
    		str =g.setEngText("对 Abc 任意字串中首字母大写加回车").formatStringAddEnterByString("abc").getEngText();
    		assertEquals("对\n abc 任意字串中首字母大写加回车", str);
    		str =g.setEngText("对 abc 任意字串中首字母小写加回车").formatStringAddEnterByString("Abc").getEngText();
    		assertEquals("对\n abc 任意字串中首字母小写加回车", str);
    		list  = new ArrayList();
    		list.add("多个");
    		list.add("大写");
    		str =g.setEngText("对 多个 任意字串中首字母 大写 加回车").formatStringAddEnterByList(list).getEngText();
    		assertEquals("对\n 多个 任意字串中首字母\n 大写 加回车", str);
    		
    	}
    
    	
    
    }
    
    
  9. #1 楼 · 抛出异常的爱 · 2008-11-13 18:48
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    
    import org.apache.commons.collections.Transformer;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.io.FileUtils;
    
    
    
    
    
    public     class   GoogleTranslationEngine    implements Transformer  {
         
          // 定义互译语言对常数变量,符合google页面相关对译语言对的值
          public   static   final  String LANGPAIR_CN_EN = "zh-CN|en" ; // 汉语到英语
          public   static   final  String LANGPAIR_EN_CN = "en|zh-CN" ; // 英语到汉语
          public   static   final  String LANGPAIR_KO_CN = "ko|zh-CN" ; // 朝鲜语到汉语
          public   static   final  String LANGPAIR_EN_JA = "en|ja" ; // 英语到日语
         
          // 定义编码常数
          public   static   final  String CHARSET_CN = "GBK" ;
          public   static   final  String CHARSET_JA = "Shift_JIS" ;
         
          // google在线翻译引擎url
          static   final  String engineUrl = "http://translate.google.com/translate_t" ; 
    
         public String translateE2C(String theword) throws HttpException, IOException{
       	  HttpClient client = new HttpClient();
    	  client.getHostConfiguration().setHost("translate.google.com",80,"http");
    		  PostMethod post;
    		  post = new PostMethod("/translate_t");
    				  NameValuePair f01 = new NameValuePair("text",theword);
    				  NameValuePair f02 = new NameValuePair("langpair",LANGPAIR_EN_CN);
    		  post.setRequestBody(new NameValuePair[]{f01,f02});
    	  client.executeMethod(post);
    	  String result = post.getResponseBodyAsString();
    	  
    
    	  post.releaseConnection();
    	  Pattern p = Pattern.compile("<div id=result_box(.*?)>(.*?)</div>"); 
    	  Matcher m = p.matcher(result);
    		 if (m.find()){
    			 return m.group(2);
    		 }
        	 return "";
         }
         public String formatFile1(String filename) throws IOException{
        	 List list = FileUtils.readLines( new File(filename),"UTF-8");
        	 StringBuffer buffer = new StringBuffer();
        	 Iterator<String> it = list.iterator();
        	 while(it.hasNext()){
        		 buffer.append(it.next());
        	 }
        	return buffer.toString();    	 
         }
         public String formatFile2(String fileInfo){
        	return fileInfo.replaceAll("\\.","\\.\n");    	
         }
    
         public void readFile(String filename) throws IOException, InterruptedException{
        	 FileUtils.writeStringToFile(new File(filename), formatFile2(formatFile1(filename)),"UTF-8");
        	 List list = FileUtils.readLines( new File(filename),"UTF-8");
        	Iterator<String> it  = list.iterator();
        	StringBuffer buffer = new StringBuffer();
        	String tmp;
        	while(it.hasNext()){
        		tmp =it.next();
        		buffer.append(tmp+"|");
        		buffer.append(translateE2C(tmp)+"\n");
        		buffer.append("\n");
    //    		Thread.currentThread().sleep(5*1000);   
        	}
        	FileUtils.writeStringToFile(new File(filename+".zhn"), buffer.toString(), "UTF-8");
         }
          public   static   void  main(String[] args)  throws  Exception {
        	GoogleTranslationEngine e = new GoogleTranslationEngine();
    
    
    
        	 e.readFile("test.eng");
    //     	System.out.println(e.translateK2C("경영위원회"));   	 
         }
    //      public static String getUnicode(String input) {
    //    	  byte[] pa2 = new byte[input.length() / 2];
    //    	  byte[] pa3 = input.getBytes();
    //    	  for (int i = 0; i < (input.length() / 2); i++) {
    //    	   pa2[i] = uniteBytes(pa3[i * 2], pa3[i * 2 + 1]);
    //    	  }
    //    	  try {
    //    	   input = new String(pa2, "utf8");
    //    	  } catch (Exception e) {
    //
    //    	  }
    //    	  return input;
    //    	 }
    //
    //    	 private static byte uniteBytes(byte src0, byte src1) {
    //    	  byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();
    //    	  _b0 = (byte) (_b0 << 4);
    //    	  byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();
    //    	  byte ret = (byte) (_b0 ^ _b1);
    //    	  return ret;
    //    	 } 
          
    	private Object translateK2C(String theword) throws HttpException, IOException {
    	   	  HttpClient client = new HttpClient();
    		  client.getHostConfiguration().setHost("translate.google.com",80,"http");
    			  PostMethod post;
    			  post = new PostMethod("/translate_t");
    					  NameValuePair f01 = new NameValuePair("text",theword);
    					  NameValuePair f02 = new NameValuePair("langpair",LANGPAIR_KO_CN);
    			  post.setRequestBody(new NameValuePair[]{f01,f02});
    		  client.executeMethod(post);
    		  String result = post.getResponseBodyAsString();
    		  
    
    		  post.releaseConnection();
    		  Pattern p = Pattern.compile("<div id=result_box(.*?)>(.*?)</div>"); 
    		  Matcher m = p.matcher(result);
    			 if (m.find()){
    				 return m.group(2);
    			 }
    	    	 return "";
    	}
    	public Object transform(Object obj){
    		try {
    			return translateE2C(obj.toString());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return "";
    		
    	}
     } 
    
    
    import static org.junit.Assert.assertEquals;
    
    import java.io.File;
    import java.io.IOException;
    
    import org.apache.commons.io.FileUtils;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.BeforeClass;
    import org.junit.Test;
    
    
    public class GoogleTranslationEngineTest {
    	String filename = "testFormatFile";
    	GoogleTranslationEngine g;
    	@BeforeClass
    	public static void setUpBeforeClass() throws Exception {
    	}
    
    	@Before
    	public void setUp() throws Exception {
    		g = new GoogleTranslationEngine();
    		FileUtils.writeStringToFile(new File(filename), "a\nb\nc", "UTF-8");
    	}
    
    	@After
    	public void tearDown() throws Exception {
    		new File(filename).delete();
    	}
    
    	@Test
    	public void test去掉回车变成一行() throws IOException {
    		String str =g.formatFile1(filename);
    		assertEquals("abc", str);
    		
    	}
    	@Test
    	public void test在每个句号后加回车(){
    		String str = g.formatFile2("abc.acd");
    		assertEquals("abc.\nacd", str);
    		
    	}
    	
    
    }
    

    明天把韩文的搞定 PS:如果有人有韩文,或日文编程经验 PM我 我遇到了转码问题.

评论功能维护中,当前仅展示历史评论。