【问题标题】:String.replace() with special characters only replacing some of them带有特殊字符的 String.replace() 仅替换其中一些字符
【发布时间】:2020-12-11 07:17:14
【问题描述】:

我在这个站点和其他站点上查看了许多关于替换字符的不同帖子,并且我之前已经完成了字符串替换。然而,在这个特定的例子中,我遇到了一个意想不到的问题。我希望我只是遗漏了一些明显的东西......

我正在尝试用其 HTML 实体代码替换特殊字符列表。我已经尝试了几个版本,从纯文本替换(½½)到最后一次迭代,使用字节编码字符串(建议 here

我的代码的功能非常简单。我得到一个文件的内容:

with open(cur_file, 'r', encoding='utf-8') as file_handle:
    file_contents = file_handle.read()
file_handle.close()

然后我调用我的“replacer()”函数:

good_text = replacer(file_contents)

replacer() 函数内容:

def replacer(text):
    replace_chars = {
        b'\xc2\xbd': '½',    #½
        b'\xe2\x80\x9c': '"',  #“
        b'\xe2\x80\x9d': '"',  #”
        b'\xe2\x80\x99': '´', #’
        b'\xe2\x80\x93': '—', #–
        b'\xc2\xa9': '©'       #©
    }
    
    for k, v in replace_chars.items():
        good_text = text.replace(k.decode('utf-8'), v)
        print('replacing ' + k.decode('utf-8') + ' with ' + v)
    return good_text

然后我将新文本保存回文件中:

    with open(cur_file, 'w', encoding='utf-8') as file_handle:
        file_handle.write(good_text)
    file_handle.close()
    
    print('Done!')

在控制台中,我运行它并得到:

replacing ½ with ½
replacing “ with "
replacing ” with "
replacing ’ with ´
replacing – with —
replacing © with ©
Done!

这符合预期。但是,我要替换其中的字符串的文件具有以下内容:

replace_chars = {
        '½': '½',
        '“': '"',
        '”': '"',
        '’': '´',
        '–': '—',
        '©': '©'

我希望文件不包含½ 或第一列中的其他字符,而是类似于'©': '©'

【问题讨论】:

    标签: python html


    【解决方案1】:

    每次循环时,您都是从原始文本替换,而不是前一次替换的结果。所以最终的结果只是最后一个替换,不是全部替换。

    更改循环,以便将结果存储回同一个变量中。

        for k, v in replace_chars.items():
            text = text.replace(k.decode('utf-8'), v)
            print('replacing ' + k.decode('utf-8') + ' with ' + v)
        return text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      相关资源
      最近更新 更多