gpt4 book ai didi

java - Python 到 java 的转换

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:50 25 4
gpt4 key购买 nike

我的原始 python 脚本如下。

#!/usr/bin/env python

import math,sys
import json
import urllib

def gsearch(searchfor):
query = urllib.urlencode({'q': searchfor})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
search_response = urllib.urlopen(url)
search_results = search_response.read()
results = json.loads(search_results)
data = results['responseData']
return data

args = sys.argv[1:]
m = 45000000000
if len(args) != 2:
print "need two words as arguments"
exit
n0 = int(gsearch(args[0])['cursor']['estimatedResultCount'])
n1 = int(gsearch(args[1])['cursor']['estimatedResultCount'])
n2 = int(gsearch(args[0]+" "+args[1])['cursor']['estimatedResultCount'])

我正在将它转换成java。我已经完成了以下所有操作。我被困在这里 search_results = search_response.read() results = json.loads(search_results) data = results['responseData'] 。我不知道如何将这3行转换成java。

import java.io.*;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.net.URLConnection;

public class gi {

public static void main (String[] args) {

if(args.length==2){

for(int i = 0; i < args.length; i++) {
System.out.println("I IS : "+i+":"+args[i]);
}
int n0 = searchGoogle(args[0]);
int n1 = searchGoogle(args[1]);
int n2 = searchGoogle(args[0]+" "+args[1]);
}
else{
System.out.println("Not enough arguement");
}
}
public static int searchGoogle(String searchQuery)
{
try{

String query=URLEncoder.encode(searchQuery, "UTF-8");
String url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s" + query;
URLConnection connection = new URL(url).openConnection();
}
catch(Exception e){
}
int pageQty=0;
return pageQty;
}

} // end of ReadString class

最佳答案

您应该能够使用类似以下内容来完成这项工作(来自 this stack overflow answer )。

String a = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s";
url = new URL(a);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
<小时/>

一旦您从 URLConnection 获得了 BufferedReader,您就可以get a String object from it :

StringBuilder builder = new StringBuilder();
String aux = "";

while ((aux = reader.readLine()) != null) {
builder.append(aux);
}

String text = builder.toString();
<小时/>

获得 String 对象后,您可以将其传递到 JSONObject 构造函数中。 (来自this stack overflow answer)。

使用org.json库:

JSONObject jsonObj = new JSONObject(text);
<小时/>

现在您已经有了 JSONObject,您可以使用可用的方法来提取所需的数据。

例如:

JSONObject cursorObj = jsonObj.getJSONObject("cursor");
int resultCount = cursorObj.getInt("resultCount");

关于java - Python 到 java 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21834643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com