如何编写正则表达式来搜索这样的字符串?

2024-04-25 01:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

_ntes_stocksearch_callback([{"type":"SZ","symbol":"000001","name":"a","spell":"PAYH"},{"type":"SH","symbol":"000001","name":"b","spell":"SZZS"},{"type":"FN","symbol":"000001","name":"c","spell":"HXCZHH"}])

如何编写正则表达式模式以获得如下结果:

{"type":"SZ","symbol":"000001","name":"a","spell":"PAYH"},
{"type":"SH","symbol":"000001","name":"b","spell":"SZZS"},
{"type":"FN","symbol":"000001","name":"c","spell":"HXCZHH"}

更新:

我从一个url中删除一些东西,我想让输出可以用函数处理json.loads文件(),那我该怎么办?你知道吗

import urllib2
convert_url = "http://quotes.money.163.com/stocksearch/json.do?type=&count=10&word=000001"
req = urllib2.Request(convert_url)
html = urllib2.urlopen(req).read()
html = html.decode("gbk").encode("utf-8")
print html

Tags: namejsonurlhtmltypeshurllib2symbol
1条回答
网友
1楼 · 发布于 2024-04-25 01:27:26

好的,那么API将返回一个JSONP响应。你知道吗

因此,首先您必须将格式“展开”或“转换”为普通json。我们将使用url的callback参数将JSONP函数设置为固定名称

# Setthe callback name to "n"
convert_url = "http://quotes.money.163.com/stocksearch/json.do?type=&count=10&word=000001&callback=n"

然后,我们可以删除JSON中留下的JSONP,它可以很容易地被解析

import json

def loads_jsonp(jsonp, callback_name):
    jsonp = jsonp.strip()
    if jsonp.startswith(callback_name + '(') and jsonp.endswith(')'):
        # remove the leading "callback(" and trailing ")", then parse the json
        return json.loads(jsonp[len(callback_name) + 1:-1])
    raise ValueError.new("Callback names do not match, or invalid JSONP format")

然后我们可以将其应用于我们的数据:

# `jsonp_data` variable contains the body of the response
my_data = loads_jsonp(jsonp_data, "n")

或者,您可以检查API是否能够返回常规的JSON响应,在这种情况下,我们可以跳过所有这些跳过,直接使用json.loads。你知道吗

相关问题 更多 >