[英]Python - Parse a list of string formatted list of strings
I am having problem in parsing list of strings in the below format.我在解析以下格式的字符串列表时遇到问题。 This is actually a pandas dataframe:
这实际上是一个 pandas dataframe:
def parse_text_to_list(row):
print(row) # eval is not working as inner strings are missing the quotes
return row
df.apply(parse_text_to_list)
output output
# printed only one row to simplify the question
['[[str1, str2], [str1, a long text], ..., [strn, strx]]']
But Want to convert it to a pure python list like:但想将其转换为纯 python 列表,如:
[["str1", "str2"], ["str1", "a long text"], ... ["strn", "strx"]]
@Negative markers - let me know the reason @Negative 标记 - 让我知道原因
You can try regular expression
with literal_eval
to get the list您可以尝试使用
literal_eval
的regular expression
来获取列表
import re
import ast
l = ['[[str1, str2], [str1, a long text], [strn, strx]]']
output = ast.literal_eval(re.sub(r'([^\[\],\s][^\[\],]+[^\[\],\s])', r'"\1"', l[0]))
print(output)
[['str1', 'str2'], ['str1', 'a long text'], ['strn', 'strx']]
If you want print each row as a list you can use:如果要将每一行打印为列表,可以使用:
def parse_text_to_list(row):
print(row.tolist())
return row
But if you want convert each row to List,you can use directly:但是如果你想将每一行转换为List,你可以直接使用:
df.values.tolist()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.