从 python 中提取的值创建键值对
creating a key value pairs from extracted values in python
我有一个字符串,我试图匹配文本,它按预期工作
import re
s = "This week end is very good"
v = re.findall(r'(This)',s)
print v
输出:
['This']
但是当我尝试进行多次匹配时它不起作用
import re
s = "This week end is very good"
v = re.findall(r'(This)(week)',s)
print v
输出:
[]
如何进行多重匹配,我想要像键值对一样的输出
示例输出:
"This" : "week"
您必须匹配 space 字符。试试这个:
v = re.findall(r'(This) (week)',s)
结果:
v = re.findall(r'(This) (week)',s)
print v
[('This', 'week')]
要将其转换为键值对,只需调用 dict
构造函数:
d = dict(v)
print d
{'This': 'week'}
如果您想使用多个搜索模式,您需要使用交替运算符|
。
>>> s = "This week end is very good"
>>> v = re.findall(r'This|week',s)
>>> ' : '.join(v)
'This : week'
我有一个字符串,我试图匹配文本,它按预期工作
import re
s = "This week end is very good"
v = re.findall(r'(This)',s)
print v
输出:
['This']
但是当我尝试进行多次匹配时它不起作用
import re
s = "This week end is very good"
v = re.findall(r'(This)(week)',s)
print v
输出:
[]
如何进行多重匹配,我想要像键值对一样的输出
示例输出:
"This" : "week"
您必须匹配 space 字符。试试这个:
v = re.findall(r'(This) (week)',s)
结果:
v = re.findall(r'(This) (week)',s)
print v
[('This', 'week')]
要将其转换为键值对,只需调用 dict
构造函数:
d = dict(v)
print d
{'This': 'week'}
如果您想使用多个搜索模式,您需要使用交替运算符|
。
>>> s = "This week end is very good"
>>> v = re.findall(r'This|week',s)
>>> ' : '.join(v)
'This : week'