【问题标题】:Python print regex in json stringPython在json字符串中打印正则表达式
【发布时间】:2014-06-19 23:03:20
【问题描述】:

所以,我正在使用一个小的 python 脚本来尝试简单地打印出网站 'northwest.hall.' 的每一次出现,其中通配符 () 是一个非常大的数字从 url 中提取的 json 字符串。

到目前为止,我有这个: 导入urllib、json、re

url = 'http://graphite.website.com/render/?target=stats.web.northwest.hall.*&format=json'
response = urllib.urlopen(url)
data = json.loads(response.read())
code = re.findall('northwest', data)
print code

这应该返回正在解析的 json 字符串中的 30 个正则表达式的列表 north.hall.number,但我得到以下错误:

Traceback (most recent call last):
  File "/Users/arin/Desktop/scripts/code_parser2.py", line 7, in <module>
    code = re.findall('community', data)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 177, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer

Python 新手(你肯定知道)。 提前致谢。

【问题讨论】:

  • 您是否验证了您所提取的数据与您在应用正则表达式之前所认为的一样?
  • 当我尝试你的 URL 时,我得到了404 - File or directory not found
  • 我也得到了404,所以我使用httpbin.org/headers从服务器httpbin.org获取一些json

标签: python regex json


【解决方案1】:

使用

data = response.read()

从服务器获取json字符串。

使用

data = json.loads(response.read())

你把这个字符串改成 python 字典。


编辑:

import re

data = """
stats.web.northwest.hall.01
stats.web.northwest.hall.223
stats.web.northwest.hall.31
stats.web.northwest.hall.4
"""

print re.findall(r'stats.web.northwest.hall.(\d+)', data)

['01', '223', '31', '4']

【讨论】:

  • 令人敬畏的 furas,总是让专业人士感到谦卑。我得到了 30 个“西北”实例。如何获得字符串 stats.web.northwest.hall 后面的数字。 ?再次感谢!
  • 你的意思是像我回答中的例子吗?
  • 完美!如果你在旧金山,我想给你买杯啤酒。事实上,很多。
  • 旧金山对我来说太远了:(我来自欧洲的波兰;)
猜你喜欢
  • 2013-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-10
相关资源
最近更新 更多