【问题标题】:Replacing substring with dictionary value if it matches with the keys如果它与键匹配,则用字典值替换子字符串
【发布时间】:2020-11-09 10:49:44
【问题描述】:

我也有字典和字符串,我想用字典值替换子字符串。我正在使用以下代码,但没有得到预期的结果。

dict1 = {'name1': 'Orange', 'name2': 'Apple', 'name3': 'Carrot', 'name4': 'Mango'}
a ="Fruit: name1    Fruit: name2    Fruit: name5    Fruit: name3    Fruit: name5"
print(a)
a_new = ''
for key in dict1.keys():
    skey = a[a.find(': ') + 2 : a.find(' F')].strip()
    if skey == key:
        sval = dict1[key]
        a_new = a[ : a.find(': ') + 1] + sval + a[a.find(' F') : ]
print(a_new)

我的代码输出

Fruit: name1     Fruit: name2     Fruit: name5     Fruit: name4     Fruit: name5 
Fruit:Orange Fruit: name2     Fruit: name5     Fruit: name4     Fruit: name5

我的预期输出

Fruit: name1     Fruit: name2     Fruit: name5     Fruit: name4     Fruit: name5 
Fruit: Orange     Fruit: Apple     Fruit: name5     Fruit: Carrot     Fruit: Mango

感谢您的帮助。提前致谢。

【问题讨论】:

  • 您想将子字符串与从头到尾的连续键匹配还是要检查它是否与任何键匹配?
  • 我只想检查子字符串是否与字典键匹配。

标签: python-3.x string dictionary


【解决方案1】:

嗯,你非常接近你的预期输出。我在某处编辑了您的代码并获得了预期的输出,尽管您也可以使用正则表达式来完成。 find返回与子字符串的第一个匹配项,在您的情况下,您需要移动您的 find 搜索位置。

find(substring, start_position, end_position)

修改后的代码

dict1 = {'name1': 'Orange', 'name2': 'Apple', 'name3': 'Carrot', 'name4': 'Mango'}
a ="Fruit: name1    Fruit: name2     Fruit: name5    Fruit: name3    Fruit: name5"
offset1 = 0
offset2 = 0
print(a)
for key in dict1.keys():
    skey = a[a.find(': ', offset1) + 2 : a.find(' F', offset2)].strip()
    if skey in dict1.keys():
        sval = dict1[key]
        a = a[ : a.find(': ', offset1) + 2] +sval + '\t' + a[a.find(' F', offset2) : ]
    offset1 = a.find(': ', offset1) + 1
    offset2 = a.find(" F", offset2) + 1
print(a)

输出

Fruit: name1    Fruit: name2     Fruit: name5    Fruit: name3    Fruit: name5
Fruit: Orange    Fruit: Apple    Fruit: name5    Fruit: Mango    Fruit: name5

【讨论】:

    【解决方案2】:

    您可以使用正则表达式来查找匹配项并使用它来替换字符串中的匹配词。

    import re
    
    dict1 = {'name1': 'Orange', 'name2': 'Apple', 'name3': 'Carrot', 'name4': 'Mango'}
    a ="Fruit: name1 \
        Fruit: name2 \
        Fruit: name5 \
        Fruit: name4 \
        Fruit: name5 \
    "
    pattern = re.compile(r"\w+:\s+(\w+)")
    match = re.findall(pattern, a)
    for item in match:
        if item in dict1.keys():
            a = a.replace(item, dict1[item])
    print(a)
    

    输出:

    'Fruit: Orange     Fruit: Apple     Fruit: name5     Fruit: Mango     Fruit: name5 '
    

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 1970-01-01
      • 2020-08-04
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 2018-01-02
      相关资源
      最近更新 更多