如何在python中转义括号

2024-04-20 09:50:40 发布

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

我是编程新手。本练习的目标是将字符串转换为新字符串,其中新字符串中的每个字符都是“(“如果该字符在原始字符串中仅出现一次,或者”)(如果该字符在原始字符串中出现多次)。确定字符是否重复时忽略大小写

但当代码遇到右括号时,它会生成错误的输出。我发现,问题在于正则表达式,但我不知道如何修复代码

from collections import Counter

def duplicate_encode(word):
    counter = Counter(word.lower())
    counter2 = dict.copy(counter)

    print(counter2)

    for k,v in counter2.items():
        if counter2[k]==1:
            counter2[k]='('
        else:
            counter2[k]=')'
  
    for key in counter2.keys():
        word = str(word.lower()).replace(key, str(counter2[key])) 
    
    return word

例如:

duplicate_encode('yy! R)!QvdG')应该返回)))((()((((,但是我得到了(((((((((((


Tags: key字符串代码infor编程counter字符
3条回答
from collections import Counter


def duplicate_encode(word):
    res = list(word.lower())
    counter = Counter(word.lower())
    counter2 = dict.copy(counter)

    print(counter2)

    for k, value in enumerate(res):
        if counter2[value] == 1:
            res[k] = '('
        else:
            res[k] = ')'

    # for key in counter2.keys():
    #     word = str(word.lower()).replace(key, str(counter2[key]))

    return "".join(res)


res = duplicate_encode('yy! R)!QvdG')
print("res", res)

当输入字符串包含大括号(如())时,就会出现问题。
当这种情况发生时,就像在您的示例中一样,错误的字符会被替换,您可以在每次更改word时通过在代码中添加print()语句来验证这一点。
我已经替换了你代码中的那个部分

from collections import Counter

def duplicate_encode(word):
    counter = Counter(word.lower())
    counter2 = dict.copy(counter)

    print(counter2)

    for k,v in counter2.items():
        if counter2[k]==1:
            counter2[k]='('
        else:
            counter2[k]=')'
    
    print(counter2)
    
    new_word = ''
    for character in word:
        new_word += counter2[character.lower()]
    
    return new_word

但是,请注意,代码有相当多的冗余和不必要的内存使用。可以简化为以下内容:

from collections import Counter

def duplicate_encode(word):
    lower_word = word.lower()
    new_word = ''
    counter = Counter(lower_word)
    
    for char in lower_word:
        if counter[char] > 1:
            new_word += ')'
        else:
            new_word += '('
    
    return new_word

另一个解决方案。从一组(唯一)字符开始,循环字符串中的字符,从该集中删除该字符,如果已删除该字符,则该字符必须是重复的。使用此选项可建立一组重复字符

def duplicate_encode(word):
    word = word.upper()
    s = set(word)
    dups = set()

    for char in word:
        if char in s:
            s.remove(char)
        else:
            dups.add(char)

    return "".join(")" if char in dups else "("
                   for char in word)

print(duplicate_encode("'yy! R)!QvdG'"))

给出:

))))((()(((()

相关问题 更多 >