我有一個對象,看起來像 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'}]
訪問片Python對象中
我想內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'}]
我試過
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
修正了,謝謝。如果我試圖抓取的物品的長度不同,並且可能超過兩個字符,以至於說'抓(..)'不會總是有效......我怎麼能適應這個? – nquestion
所以,如果你想捕捉兩個以上的項目,你可以修改你的正則表達式像這樣:(。*) - >匹配零個或無字符 - >匹配一個或多個字符 ((+)。 {x}) - >匹配x個字符的實例。 如果你谷歌「正則表達式備忘單」,你會發現有用的指南正則表達式的語法。 – patrick