1.首先下载Jython包,链接为:Download Jython 2.7.0 - Standalone Jar
2.下载完成之后,添加到java的工程中,添加工程参考博客
3.编写python函数,本次编写的函数主要用于爬取一个笑话网页的笑话,代码如下:
# -*- coding: utf-8 -*-
import urllib2
import re
import os
def myStory(title_Content,number):
xx =urllib2.urlopen("http://www.haha365.com/joke/index_1.htm")
data = xx.read().decode('GBK')
patter = re.compile("<h3><A href.*?>(.*?)</a></h3>",re.S)
patter1 = re.compile("<div id=\"endtext\">(.*?)</div>",re.S)
res = re.findall(patter,data)
resText = re.findall(patter1,data)
for i in range(len(resText)):
resText[i] = resText[i].replace("<br />","")
resText[i] = resText[i].replace("&ldquo","")
resText[i] = resText[i].replace("&rdquo", "")
resText[i] = resText[i].replace("</p>", "")
resText[i] = resText[i].replace("<p>", "")
if title_Content==1:
return res[number]
else:
return resText[number]
4.编写java端函数:
package guitest;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyObject.ConversionException;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
public class FirstJavaScript {
public static void main(String args[]) throws UnsupportedEncodingException, ConversionException {
Properties props = new Properties();
props.put("python.console.encoding", "utf-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site", "false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
//python文件路径
interpreter.execfile("F:/whg/whg.py");
//获取python文件中的函数
PyFunction func = interpreter.get("myStory",
PyFunction.class);
//调用函数
PyObject title = func.__call__(new PyString("12"),new PyInteger(1),new PyInteger(10));
PyObject content = func.__call__(new PyString("12"),new PyInteger(2),new PyInteger(10));
//输出内容
System.out.println(title.toString());
System.out.println(content.toString());
}
}
5.运行之后,输出的结果为:
笑话名字:还真没你啥事
笑话内容:昨晚和一哥们喝酒,突然就问他最近婚姻感情怎么样,哥们平淡道:没啥问题,就是换了几位丈母娘。
我佩服的五体投地:可以啊,神人啊。
哥们不平道:没我啥事,TMD,是我岳父厉害!