簡體   English   中英

從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"

您必須匹配空格字符。 嘗試這個:

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM