python - 在字符串中的关键字之前删除 '\n'

标签 python regex pandas dictionary

我有以下字符串:

elements = "one: Fire \n two: Water \n three: Earth \n four: \n Sky \n five: \n Light \n"

我想动态分割线以得到如下字典形状:

{one: Fire, 
two: Water, 
three: Earth, 
four: Sky, 
five: Light}

我可以使用 re.findall() 对前三个元素执行此操作,因为信息包含在新行拆分之前。 但是对于“四:”和“五:”元素前有一个“\n”,我无法提取该元素。

有没有办法动态地做到这一点?

我能想到的唯一解决方案是过滤元素单词列表前的“\n”。

最佳答案

您可能不需要复杂的正则表达式来执行此操作。你可以试试这个

str = 'one: Fire \n two: Water \n three: Earth \n four: \n Sky \n five: \n Light \n'
str = str.replace(' ', '').replace(':\n', ':')
parts = filter(lambda x: ':' in x, str.split('\n'))
elements = dict((elem.split(':')) for elem in parts)
print(elements)

但如果你真的想花哨,这也行

import re
str = 'one: Fire \n two: Water \n three: Earth \n four: \n Sky \n five: \n Light \n'
parts = map(lambda x: re.sub('\s', '', x), re.findall('\w+:\s*\w+', str))
elements = dict((elem.split(':')) for elem in parts)
print(elements)

关于python - 在字符串中的关键字之前删除 '\n',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59290508/

相关文章:

python - 如何限制Python列表中元素的数量

python - 没有找到模块错误 : No module named 'distributed'

python - 读取 Flask Web 服务的参数

PHP 删除网址字符串中包含 .html 之后的所有内容

regex - 使用 grep 进行负匹配(匹配不包含 foo 的行)

python - 多索引情况下每个索引的列总和

Python图表-更改轴标记颜色和图例边框颜色

ruby - 字符串中的反斜杠返回两个反斜杠

python - 删除具有任何/所有 NaN 值的行/列

python - 查看列表中每个元素的字符串的第一个字符