简体   繁体   中英

Extract specific words from String in python

I want to extract all the words that are before "indices" (ie ForeverTrophyless, NoPainNoGame, Prize) and put em all inside a list. How Can I do that?

foo = '[{"text":"ForeverTrophyless","indices":[0,18]},{"text":"ForeverTrophyless","indices":[19,37]},{"text":"Prize","indices":[38,56]},{"text":"ForeverTrophyless","indices":[57,75]},{"text":"NoPainNoGame","indices":[76,94]},{"text":"ForeverTrophyless","indices":[95,113]},{"text":"ForeverTrophyless","indices":[114,132]}]'

Python2.7

Pycharm Ubuntu 14.04

You can use ast.literal_eval to turn that string into a list of dictionaries.

foo = '[{"text":"ForeverTrophyless","indices":[0,18]},{"text":"ForeverTrophyless","indices":[19,37]},{"text":"Prize","indices":[38,56]},{"text":"ForeverTrophyless","indices":[57,75]},{"text":"NoPainNoGame","indices":[76,94]},{"text":"ForeverTrophyless","indices":[95,113]},{"text":"ForeverTrophyless","indices":[114,132]}]'

import ast
l = ast.literal_eval(foo)

l is now:

[{'indices': [0, 18], 'text': 'ForeverTrophyless'},
 {'indices': [19, 37], 'text': 'ForeverTrophyless'},
 {'indices': [38, 56], 'text': 'Prize'},
 {'indices': [57, 75], 'text': 'ForeverTrophyless'},
 {'indices': [76, 94], 'text': 'NoPainNoGame'},
 {'indices': [95, 113], 'text': 'ForeverTrophyless'},
 {'indices': [114, 132], 'text': 'ForeverTrophyless'}]

Then use a list comprehension

[i['text'] for i in l]

Result

['ForeverTrophyless', 'ForeverTrophyless', 'Prize', 'ForeverTrophyless', 'NoPainNoGame', 'ForeverTrophyless', 'ForeverTrophyless']

foo appears to be a valid serialized JSON object. You can parse it with json.loads and then retrieve all text fields inside a list comprehension:

In [8]: from json import loads

In [9]: [x['text'] for x in loads(foo)]
Out[9]: 
['ForeverTrophyless',
 'ForeverTrophyless',
 'Prize',
 'ForeverTrophyless',
 'NoPainNoGame',
 'ForeverTrophyless',
 'ForeverTrophyless']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM