Py学习  »  Python

Python阅读了一系列妄想中的妄想的第一个条目

Chelsea-fc • 3 年前 • 1336 次点击  

我有以下样本的数千行。

“[('entryA','typeA'),('entryB','typeB'),('entryC','typeC'), ('entryD','typeD')”

我的问题是如何提取每个括号的第一个条目,并将其置于以下格式?

“条目”:[“entryA”、“entryB”、“entryC”、“entryD”]

我的代码:

s = "[('entryA', 'typeA'), ('entryB', 'typeB'), ('entryC', 'typeC'), ('entryD', 'typeD')]"
result = re.findall('\(\'.*?,', s)

print("\"entries\":",result)

电流输出:

“条目”:[“('entryA',”,“('entryB',”,“('entryC',”,“('entryD',”]

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132132
 
1336 次点击  
文章 [ 3 ]  |  最新文章 3 年前
Epsi95
Reply   •   1 楼
Epsi95    3 年前

你不需要 re 使用 ast.literal_eval

>>> s = "[('entryA', 'typeA'), ('entryB', 'typeB'), ('entryC', 'typeC'), ('entryD', 'typeD')]"
>>> from ast import literal_eval
>>> literal_eval(s)
[('entryA', 'typeA'), ('entryB', 'typeB'), ('entryC', 'typeC'), ('entryD', 'typeD')]
>>> out = [i[0] for i in literal_eval(s)]
>>> out
['entryA', 'entryB', 'entryC', 'entryD']
Tim Roberts
Reply   •   2 楼
Tim Roberts    3 年前

这里有一个更好的方法。

import ast
s = ast.literal_eval(s)
entries = [a[0] for a in s]
Ibrahim
Reply   •   3 楼
Ibrahim    3 年前

您需要使用lookahead和lookback正则表达式来执行以下操作

s = "[('entryA', 'typeA'), ('entryB', 'typeB'), ('entryC', 'typeC'), ('entryD', 'typeD')]"
result = re.findall("(?<=\(').*?(?=',)", s)

print("\"entries\":",result)

展望未来: (?=EXPR) 查看元素正前方的内容。
回顾: (?<=EXPR) 查看元素的正后方。