如何查找/替换和忽略编码

时间:2016-12-21 18:12:06

标签: python encoding replace utf-8 ascii

我想将ascii字符串就地替换为文件列表。

我最初尝试过fileinput,但收到了这条糟糕的消息:

UnicodeEncodeError: 'ascii' codec can't encoder character u'\u026a'...

所以我写了这个:

for f in ls_files(repo.tree()):
    copyfile(f, f + '.bak')
    with open(f, 'w') as dst:
        with open(f + '.bak') as src:            
            for line in src:
                newline = line.decode('utf-8', 'ignore')
                for a, b in changes:
                    newline = newline.replace(a, b)                    
                dst.write(newline)

问题与encode / decode声明一起出现。

如果我放dst_write(newline.encode('utf-8'))我没有错误,但所有重音都会从处理过的文件中删除。没有encode('utf-8')我在某些文件上出错。

当我更换ascii时,我真的不明白为什么我需要关心编码。

使用binary读取的不同方法我也会得到相同的错误:

for f in ls_files(repo.tree()):
    copyfile(f, f + '.bak')
    print "Processing %s ..." % f,
    with open(f, 'wb') as dst:
        with open(f + '.bak', 'rb') as src:  
            content = src.read()           
            for a, b in changes:
                content = content.replace(a, b)                
            dst.write(content)

如何将ascii内容替换为我的文件而不会出现任何问题,因为我可以使用perlsed执行此操作:

$ perl -pi -e s/foo/bar/g any_type_of_file

修改

似乎可以使用

content = content.replace(bytes(a), bytes(b)) 

但是......它很难看......

0 个答案:

没有答案