Python: Parsing a complex string into usable data for analysis

Steve

Is it possible to parse the below string, using Python, or convert it into another data structure so that each element can be accessed for analysis?

This is an example line from a large text file where each line has the same format.

string = ["('a', '1')", "('b', '2')"]
Alex Riley

If you simply want to convert the tuple-strings to tuples, you can use ast.literal_eval:

>>> import ast
>>> [ast.literal_eval(x) for x in string]
[('a', '1'), ('b', '2')]

Use of ast.literal_eval rather than eval is encouraged as it is considered safer: it does not execute all strings of Python code, only literal expressions (no variables, no function calls).

You can then access the elements of the tuples using Python's slice/index notation, or convert to an alternative data structure, e.g. a dictionary:

>>> dict([ast.literal_eval(x) for x in string])
{'a': '1', 'b': '2'}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

parsing csv string in python

From Java

Parsing a string in Python

From Dev

Parsing a string intelligently to construct complex api calls

From Dev

best practice for parsing a complex json string

From Dev

Parsing complex and changing JSON data in Python, several levels deep

From Dev

Complex string parsing in Javascript

From Dev

Python argparse: Complex Argument Parsing Scenario

From Dev

Parsing JSON to something usable

From Dev

Parsing complex operands in boolean expressions in Python 2.7

From Dev

Parsing data from a string

From Dev

Optimizing string parsing with Python

From Dev

Parsing a string pattern - Python

From Dev

Cleaning data in R: parsing a complex string

From Dev

Parsing complex JSON with Python

From Dev

Parsing a string output into python data structures

From Dev

Parsing string list in python

From Dev

Parsing a string for data sets

From Dev

Android XML parsing with complex data

From Dev

Parsing complex and changing JSON data in Python, several levels deep

From Dev

Parsing XML string with python

From Dev

Parsing complex data to two dimensional array

From Dev

Parsing data from a string

From Dev

python regex parsing data from extremely complicated ingredients string

From Dev

Python regex for a complex string

From Dev

Cleaning data in R: parsing a complex string

From Dev

Parsing complex JSON with Python

From Dev

Parsing Instagram json data to usable variable in php

From Dev

Parsing Complex Mathematical Functions in Python

From Dev

Python: Solving a complex scenario analysis