如何转义括号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')应该回来)))((()((((但我得到了(((((((((((。


呼唤远方
浏览 266回答 3
3回答

狐的传说

另一个解决方案。从一组(唯一的)字符开始,遍历字符串中的字符,从该组中删除字符,如果它已经被删除,那么它必须是重复的。使用它来构建一组重复的字符。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'"))给出:))))((()(((()

跃然一笑

from collections import Counterdef 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)

慕桂英4014372

(当您的输入字符串包含大括号(如or )时,就会出现问题)。当发生这种情况时,就像在您的示例中一样,错误的字符将被替换,您可以通过print()在代码中添加语句来验证,每次更改时word。我已经在你的代码中替换了那部分。from collections import Counterdef 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 Counterdef 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python