[英]How to extract specific text and some extra characters from a string in python?
假设我有一个文本:
"background-color: #ffffe5;\n color: #000000;\n }{\n background-color: #ed7215;\n color:
#000000; background-color: #662506;\n color: #f1f1f1;"
我想提取一些包含以下内容的字典:
string1 = {background-color: #ffffe5}
string2 = {background-color: #ed7215}
string3 = {background-color: #662506}
文本通常会更长,因此有更多的背景 colors,有没有办法获得所有这些。 我知道这应该用re
来完成,但我不知道如何用这个" ".join(string.split())
我知道我可以用它来删除可以简化问题的不必要的空格,但我仍然没有任何想法。任何帮助都会很棒。 或按顺序列出 colors 的列表会很酷,但只有背景 colors。
使用re.findall
:
import re
text = '''"background-color: #ffffe5;\n color: #000000;\n }{\n background-color: #ed7215;\n color: #000000; background-color: #662506;\n color: #f1f1f1;"'''
out1 = re.findall('background-color:\s*[^;]+', text)
# OR
out2 = re.findall('background-color:\s*([^;]+)', text)
Output:
>>> out1
['background-color: #ffffe5',
'background-color: #ed7215',
'background-color: #662506']
>>> out2
['#ffffe5', '#ed7215', '#662506']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.