Эффективный разбор строк в Python - PullRequest
1 голос
/ 15 февраля 2012

В настоящее время у меня есть этот код, который анализирует http: imdbAPI:

text = 'unicode: {"Title":"The Fountain","Year":"2006","Rated":"R","Released":"22 Nov 2006","Genre":"Drama, Romance, Sci-Fi","Director":"Darren Aronofsky","Writer":"Darren Aronofsky, Darren Aronofsky","Actors":"Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn","Plot":"Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg","Runtime":"1 hr 36 mins","Rating":"7.4","Votes":"100139","ID":"tt0414993","Response":"True"}'

def stripData(tag="Title"):
    tag_start = text.find(tag)
    data_start = tag_start + len(tag)+3
    data_end = text.find('"',data_start)
    data = text[data_start:data_end]
    return tag, data  

Мне интересно: есть ли лучший способ сделать это, которого мне не хватает?

Ответы [ 3 ]

5 голосов
/ 15 февраля 2012
>>> ast.literal_eval(text.split(' ', 1)[1])
{'Plot': 'Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.', 'Votes': '100139', 'Rated': 'R', 'Response': 'True', 'Title': 'The Fountain', 'Poster': 'http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg', 'Writer': 'Darren Aronofsky, Darren Aronofsky', 'ID': 'tt0414993', 'Director': 'Darren Aronofsky', 'Released': '22 Nov 2006', 'Actors': 'Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn', 'Year': '2006', 'Genre': 'Drama, Romance, Sci-Fi', 'Runtime': '1 hr 36 mins', 'Rating': '7.4'}

>>> json.loads(text.split(' ', 1)[1])
{u'Plot': u'Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.', u'Votes': u'100139', u'Rated': u'R', u'Response': u'True', u'Title': u'The Fountain', u'Poster': u'http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg', u'Writer': u'Darren Aronofsky, Darren Aronofsky', u'ID': u'tt0414993', u'Director': u'Darren Aronofsky', u'Released': u'22 Nov 2006', u'Actors': u'Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn', u'Year': u'2006', u'Genre': u'Drama, Romance, Sci-Fi', u'Runtime': u'1 hr 36 mins', u'Rating': u'7.4'}
1 голос
/ 15 февраля 2012

Мне кажется, что все работают слишком усердно ... если у вас действительно есть

line = 'unicode: {"key1":"Value1", "key2","value2", etc...}'

которая выглядит как строка ...

затем вы удаляете "unicode:" с начала строки

newline = line[9:]

затем оцените результат непосредственно в диктовку

data_dict=eval(newline)

затем вы получаете доступ к данным с помощью ключа

print(data_dict['Title'])

У вас есть идеальное форматирование для создания диктанта Python и вы можете получить доступ к значениям непосредственно из этого контейнера.

1 голос
/ 15 февраля 2012

Вы можете попытаться привести все данные в формат после удаления всех ненужных начальных и хвостовых символов.

import re

line = 'unicode: {"Title":"The Fountain","Year":"2006","Rated":"R","Released":"22 Nov 2006","Genre":"Drama, Romance, Sci-Fi","Director":"Darren Aronofsky","Writer":"Darren Aronofsky, Darren Aronofsky","Actors":"Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn","Plot":"Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg","Runtime":"1 hr 36 mins","Rating":"7.4","Votes":"100139","ID":"tt0414993","Response":"True"}'

def parser(text):
    match = re.search(r'\{\"([^}]+)\"\}', text)
    if match:
        return dict(x.split('":"') for x in match.group(1).split('","'))

newdict = parser(line)

for k, v in newdict.items():
    print k, v

Я использую регулярное выражение, но его так же легко заменить любым методом, который удаляет до {"и после}" в найденной строке.

...