我有一个大型CSV文件,其中的行如下所示:
id_85,
{
"link": "some link",
"icon": "hello.gif",
"name": "Wall Photos",
"comments": {
"count": 0
},
"updated_time": "2012-03-12",
"object_id": "400",
"is_published": true,
"properties": [
{
"text": "University",
"name": "By",
"href": "some link"
}
],
"from": {
"id": "7778",
"name": "Let"
},
"message": "Hello World! :D",
"id": "id_85",
"created_time": "2012-03-12",
"to": {
"data": [
{
"id": "100",
"name": "March"
}
]
},
"message_tags": {
"0": [
{
"id": "100",
"type": "user",
"name": "Marcelo",
"length": 7,
"offset": 0
}
]
},
"type": "photo",
"caption": "Hello world!"
}
我试图在第一个和结束的大括号之间获取它的json部分。
以下是我目前的python正则表达式代码
import re
str = "id_85,{"link": "some link", "icon": "hello.gif", "name": "Wall Photos", "comments": {"count": 0}, "updated_time": "2012-03-12", "object_id": "400", "is_published": true, "properties": [{"text": "University", "name": "By", "href": "some link"}], "from": {"id": "777", "name": "Let"}, "message": "Hello World! :D", "id": "id_85", "created_time": "2012-03-12", "to": {"data": [{"id": "100", "name": "March"}]}, "message_tags": {"0": [{"id": "100", "type": "user", "name": "March", "length": 7, "offset": 0}]}, "type": "photo", "caption": "Hello world!"} "
m = re.match(r'.*,({.*}$)', str)
if m:
print m.group(1)
在某些情况下,它不会使用第一个和最后一个大括号,类似于此{...}。如何确保仅包含第一个和最后一个花括号之间的文本而不包含任何其他文本?
所需的输出如下所示:
{“link”:“some link”,“icon”:“hello.gif”,“name”:“Wall Photos”, “comments”:{“count”:0},“updated_time”:“2012-03-12”,“object_id”: “400”,“is_published”:true,“properties”:[{“text”:“University”, “name”:“by”,“href”:“some link”}],“from”:{“id”:“777”,“name”: “让”,“消息”:“Hello World!:D”,“id”:“id_85”,“created_time”: “2012-03-12”,“to”:{“data”:[{“id”:“100”,“name”:“March”}]}, “message_tags”:{“0”:[{“id”:“100”,“type”:“user”,“name”:“March”, “长度”:7,“偏移”:0}]},“类型”:“照片”,“标题”:“你好” 世界!“}
谢谢!
答案 0 :(得分:0)
这将匹配第一个逗号后的整个json部分。不确定这是否是你想要的。期望输出的一个例子会有所帮助。
re.match(r'[^,]*,(.*)', s).group(1)
答案 1 :(得分:0)
我相信这是有效的,因为.*
是"贪婪的"在这方面:
import re
str = 'id_85,{"link": "some link", "icon": "hello.gif", "name": "Wall Photos", "comments": {"count": 0}, "updated_time": "2012-03-12", "object_id": "400", "is_published": true, "properties": [{"text": "University", "name": "By", "href": "some link"}], "from": {"id": "777", "name": "Let"}, "message": "Hello World! :D", "id": "id_85", "created_time": "2012-03-12", "to": {"data": [{"id": "100", "name": "March"}]}, "message_tags": {"0": [{"id": "100", "type": "user", "name": "March", "length": 7, "offset": 0}]}, "type": "photo", "caption": "Hello world!"} '
m = re.search('({.*})', str)
if m:
print m.group(0)
如果你的CSV中有其他JSON字符串,那么这可能会很多地抓取 ,即它太贪心了,因为最后}
将与{{1}的最后一次出现匹配在}
请注意,符号str
- 即在正则表达式之前添加re.search(r'somregex', string)
- 称为"原始字符串表示法" - 当您希望按字面意思处理反斜杠而不是正则表达式特殊字符时,通常会使用此选项。见here。例如。 r
匹配两个字符r'\n'
和\
,而n
会匹配换行符
答案 2 :(得分:0)
假设(最初发布的)CSV中的每一行都有1个JSON元素,那么
re.match(r'^[^{]*({.*})[^}]*$',str).group(1)
应该做的伎俩。也就是说:丢弃所有不是{
的内容,直到找到第一个内容,然后放入所有内容,直到您点击}
之后没有其他}
的内容进入组中