在用python运行从hanlp官网下载的代码时,一直出错。
package hanlp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class text {
public static void main(String[] args) {
//请求头中的token
String token="59b6711ad1654141993829d3a16e0fc21683979375605token";
//申请的接口地址
String url="http://comdo.hanlp.com/hanlp/v1/word2vec/similarity";
//所有参数
Map<String,Object> params=new HashMap<String,Object>();
params.put("what", "广东");
params.put("with", "山东");
params.put("modelName", "");
//执行api
String result=doHanlpApi(token,url,params);
System.out.println(result);
}
public static String doHanlpApi(String token,String url,Map<String,Object> params) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
//添加header请求头,token请放在header里
httpPost.setHeader("token", token);
// 创建参数列表
List<NameValuePair> paramList = new ArrayList<>();
if (params != null) {
for (String key : params.keySet()) {
//所有参数依次放在paramList中
paramList.add(new BasicNameValuePair(key, (String) params.get(key)));
}
//模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
return resultString;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(response!=null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
每次会出现这种错误。
从你给的代码:
package hanlp;
import java.io.IOException;
...
看,很明显,代码是java的代码
但是你却用的是Python去运行,所以肯定会报错了。
解决办法:
对于java代码,要用java环境去运行。
关于如何运行java代码程序,网上资料很多,比如:
第一个Java程序 - 廖雪峰的官方网站
https://www.liaoxuefeng.com/wiki/1252599548343744/1255878730977024
供参考。
这是java代码,为啥用python运行