在Python对象中访问文本 [英] Access pieces of text within Python object

查看:54
本文介绍了在Python对象中访问文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像的对象 block = [{'id':'10001', 'date':'2016-01-11', 'text':'this is some text. grab 40'},{'id':'10002', 'date':'2014-03-12', 'text':'this is some more text. grab 60'}]

I have an object that looks like block = [{'id':'10001', 'date':'2016-01-11', 'text':'this is some text. grab 40'},{'id':'10002', 'date':'2014-03-12', 'text':'this is some more text. grab 60'}]

我想抓住text中的项目并重新格式化我的对象,使其看起来像: block = [{'id':'10001', 'date':'2016-01-11', 'text':'this is some text. grab 40', 'grabbed': '40'},{'id':'10002', 'date':'2014-03-12', 'text':'this is some more text. grab 60', 'grabbed': '60'}]

I would like to grab the item within text and reformat my object so it looks like: block = [{'id':'10001', 'date':'2016-01-11', 'text':'this is some text. grab 40', 'grabbed': '40'},{'id':'10002', 'date':'2014-03-12', 'text':'this is some more text. grab 60', 'grabbed': '60'}]

我尝试了

for item in block:
 if "grab" in item['text']:
         m=re.search('grab (..)',line)
 print m

但出现错误

Traceback (most recent call last): File "<stdin>", line 3, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 146, in search
return _compile(pattern, flags).search(string) TypeError: expected string or buffer

推荐答案

您的正则表达式输入已关闭:

Hi looks like the input to your regex is off:

m=re.search('grab (..)',line)

线"从哪里来?那是绳子吗?您是否不想搜索"item ['text']"? 另请注意,"re.search"将不会返回匹配项;使用例如re.findall().

Where is the "line" coming from? Is that a string? Don't you want to search over "item['text']"? Also note that "re.search" will not return matches; use e.g. re.findall().

这篇关于在Python对象中访问文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆