【问题标题】:replace substrings based on index range with dictionary values from a string用字符串中的字典值替换基于索引范围的子字符串
【发布时间】:2018-09-25 18:54:25
【问题描述】:

我有以下字符串/句子(语法不正确)

s = "The user should be able to audit log to view the audit log entries."

我有一本带有相似键的字典:

d = {'audit' : 'class1',
    'audit log' : 'class2',
    'audit log entries' : 'class3'}

我能够获取与字典中的键匹配的子字符串的索引范围,我需要替换与其值匹配的键。

   final_ranges = [(49, 66), (27, 36)] #list length may vary

我想遍历索引范围并替换子字符串。

我尝试了以下代码:

for i in final_ranges:
    for k,v in d.items():
        if s[i[0]:i[1]] == k:
            print(s[0:i[0]] + v + s[i[1]:])

将输出:

The user should be able to audit log to view the class3.
The user should be able to class2 to view the audit log entries.

但我希望子字符串替换出现在一个句子本身中。

The user should be able to class2 to view the class3.

我经历了这个link。但它不是基于索引范围。

【问题讨论】:

  • 为什么要使用索引范围? .replace() 会更简单
  • @mfitzp 索引范围是另一个代码的输出,我应该只替换那些键

标签: python arrays string python-3.x


【解决方案1】:

您实际上从未更新过s。因此,您的更改不会产生。试试这个:

for i in final_ranges:
    key = s[i[0]:i[1]]
    if (key in d):
        s = s[:i[0]] + d[key] + s[i[1]:]
        print(s)

尽管如 cmets 中所述,您可能应该使用替换:

for k, v in d.items():
    s = s.replace(k, v)
    print(s)

如果您愿意放弃 print 声明,您甚至可以将其作为列表推导:

from functools import reduce
s = reduce(lambda string, kv: string.replace(kv[0], kv[1]), d.items(), s)

【讨论】:

  • 只需要更改索引范围键。否则,由于键相似,它将替换为 class1 作为值,而不是专门替换为 class2 和 class3 作为值
猜你喜欢
  • 2016-03-23
  • 2012-12-05
  • 2010-10-31
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 2017-01-14
  • 2018-09-11
相关资源
最近更新 更多