css 如何查找和替换多个单词?

rta7y2nd  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(130)

我想找到并替换多个单词?我发现这个代码这是工作正常,但只有一个文本工作,我怎么能添加多个单词。

var observer = new MutationObserver(onMutation);
observer.observe(document, {
    childList: true, // report added/removed nodes
    subtree: true,   // observe any descendant elements
});

function onMutation(mutations, observer) {
    for (var i = 0, len = mutations.length; i < len; i++) {
        var added = mutations[i].addedNodes;
        for (var j = 0, node; (node = added[j]); j++) {
            replaceText(node);  
        }
    }
}

function replaceText(el) {
    let target_string = "winter";
    let replacement_string = "summer";

    const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
    for (let node; (node = walker.nextNode());) {
        const text = node.nodeValue;
        const newText = text.replace(target_string, replacement_string);
        if (text !== newText) {
            node.nodeValue = newText;
        }
    }
}
b09cbbtk

b09cbbtk1#

您可以尝试使用dict执行相同的代码,其中dict的键、值表示目标和替换字符串。

import re
var observer = new MutationObserver(onMutation);
observer.observe(document, {
    childList: true, // report added/removed nodes
    subtree: true,   // observe any descendant elements
});

function onMutation(mutations, observer) {
    for (var i = 0, len = mutations.length; i < len; i++) {
        var added = mutations[i].addedNodes;
        for (var j = 0, node; (node = added[j]); j++) {
            replaceText(node);  
        }
    }
}

function replaceText(el) {
    tar_rep_str = {"winter": "summer", "monsoon": "autumn"}
    rep = dict((re.escape(k), v) for k, v in tar_rep_str.items()) 

    const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
    for (let node; (node = walker.nextNode());) {
        const text = node.nodeValue;
        pattern = re.compile("|".join(rep.keys()))
        const newText = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
        if (text !== newText) {
            node.nodeValue = newText;
        }
    }
}

相关问题