[英]using regex to find and extract a pattern in a json file with python
我正在嘗試查找並提取生活在json文件中的模式。 如果我將其作為測試來執行,它將找到並打印出來,因為json.dumps將其設為字符串:
my_mi = {"_links": {"self": {"href": "/xx-beta/media/111ee111-1e11-11a1-b111/metadata"}}}
new = json.dumps(my_mi)
my_id = re.findall(r'\w{1,9}\-\w{1,5}\-\w{1,5}\-\w{1,5}\-\w{1,13}',
new)
print my_id
問題是,當我嘗試將其用作json文件時,我無法以某種方式轉換它而不會拋出錯誤"TypeError: <open file 'resTwo.json', mode 'r' at 0x1109eee40> is not JSON serializable"
,這就是以下操作:
with open ("resTwo.json", "r") as input_file:
new = json.dumps(input_file)
my_id = (re.findall(r'\w{1,9}\-\w{1,5}\-\w{1,5}\-\w{1,5}\-\w{1,13}', new))
print my_id
我以為json.dumps轉換為字符串,所以正則表達式可以像測試示例中那樣工作?
從csv閱讀器對象返回的行將是列表。 re.findall
期望將字符串作為第二個參數。
指定您要讓正則表達式匹配的字段,或者添加另一個for循環來遍歷每個字段(即遍歷row
)。
我用這個解決了:
for value in input_file:
mediaid = (re.findall(r'\w{1,9}\-\w{1,5}\-\w{1,5}\-\w{1,5}\-\w{1,13}', value))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.