用字符串中的字典值替换基于索引范围的子字符串

2024-05-12 19:02:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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。但它不是基于索引范围


Tags: theto字符串logviewableauditbe
1条回答
网友
1楼 · 发布于 2024-05-12 19:02:14

实际上你从来没有更新过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)

尽管如评论中所述,您可能应该使用replace:

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)

相关问题 更多 >