python - 列表上正则表达式过滤器后输出中的分隔符

标签 python regex list

我是 Python 新手,请耐心等待。

我有一个 list -

print(listoffiles)
["{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n"]

我只需要此列表中的文件名,

0_HONOR_1524204351030, 0_HONOR_1524204351030,0_HONOR_1524204351030

我首先这样拆分 -

listoffiles=[i.split(":")[0] for i in listoffiles]
print(listoffiles)
["{'0_HONOR_1524204351030'", "{'0_HONOR_1524204351030'", "{'0_HONOR_1524204351030'"]

然后加入它-

listoffiles=(','.join(str(f) for f in listoffiles))
print(listoffiles)
{'0_HONOR_1524204351030',{'0_HONOR_1524204351030',{'0_HONOR_1524204351030'

在这里,我试图剥离它 -

listoffiles=(str(listoffiles).strip("'{'"))
print(listoffiles)
0_HONOR_1524204351030',{'0_HONOR_1524204351030',{'0_HONOR_1524204351030'

这似乎只适用于第一个元素,所以我也尝试了 -

listoffiles=(str(f).strip("'{'") for f in listoffiles)
print(listoffiles)
<generator object <genexpr> at 0x7fda38837460>

由于效果不佳,我尝试使用正则表达式 -

regex = re.compile(r'^[a-zA-Z0-9_]*$')
newlistoffiles=filter(regex.match,listoffiles)

这个似乎有效,但我无法分离输出-

0_HONOR_15242043510300_HONOR_15242043510300_HONOR_1524204351030

我需要帮助来区分这些。 我发布了整个问题,以便我可以获得有关完成此任务的任何其他更好、更聪明的方法的建议。

最佳答案

使用 ast 模块将字符串字典转换为 python 字典,并使用 keys() 获取所需的键。

例如:

import ast
listoffiles = ["{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n"]
listoffiles = map(ast.literal_eval, listoffiles)
print([i.keys()[0] for i in listoffiles])

输出:

['0_HONOR_1524204351030', '0_HONOR_1524204351030', '0_HONOR_1524204351030', '0_HONOR_1524204351030', '0_HONOR_1524204351030']

关于python - 列表上正则表达式过滤器后输出中的分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50137307/

相关文章:

使用 RLIKE 在 Snowflake 存储过程中将 VARCHAR 值 REGEX 转换为 DATE 不一致

c# - 子字符串、搜索列表

python - 复制列表或 Numpy 数组中的特定元素

python - 当超过 100 个异步函数运行时锁定异步函数?

Python/Selenium - 如何从模态淡入淡出内容中提取文本?

python - 将参数传递给 defaultdict 创建的对象

python - Mechanize (将输入设置为表单)

java - 检查 JAVA 字符串中的模式 "1.1.7B-2"

php - 在 PHP 中,使用 "LIKE"从 MySQL 搜索结果中获取整个单词

r - 根据条件将包含列表的两列合并为一列