Python:特殊字符编码

2024-04-28 11:43:44 发布

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

这是我用来替换文本文件中的特殊字符并将它们连接到单个文件的代码。

# -*- coding: utf-8 -*-

    import os
    import codecs

    dirpath = "C:\\Users\\user\\path\\to\\textfiles"
    filenames = os.listdir(dirpath)

    with codecs.open(r'C:\Users\user\path\to\output.txt', 'w', encoding='utf8') as outfile:
        for fname in filenames:
            currentfile = dirpath+"\\"+fname
            with codecs.open(currentfile, encoding='utf8') as infile:
        #print currentfile
                outfile.write(fname)
                outfile.write('\n')
                outfile.write('\n')

                for line in infile:

                    line = line.replace(u"´ı", "i")
                    line = line.replace(u"ï¬", "fi")
                    line = line.replace(u"fl", "fl")
                    outfile.write (line)

第一个line.replace运行良好,而其他的没有(这是有道理的),并且由于没有产生错误,我认为可能存在“可见性”问题(如果这是术语的话)

import codecs

currentfile = 'textfile.txt'
with codecs.open('C:\\Users\\user\\path\\to\\output2.txt', 'w', encoding='utf-8') as outfile:
with open(currentfile) as infile:
for line in infile:
if "ï¬" not in line: print "not found!"

它总是返回“找不到!”证明那些字符没有被读取。

在第一个脚本中更改为with codecs.open('C:\Users\user\path\to\output.txt', 'w', encoding='utf-8') as outfile:时,出现以下错误:

Traceback (most recent call last):
File C:\\path\\to\\concat.py, line 30, in <module>
outfile.write(line)
File C:\\Python27\\codecs.py, line 691, in write
return self.writer.write(data)
File C:\\Python27\\codecs.py, line 351, in write
data, consumed = self.encode(object, self.errors)
Unicode DecodeError: 'ascii' codec can't decode byte 0xe7 in position 0: ordinal
not in range (128)

由于我在python方面并不是很有经验,所以我无法通过已有的不同来源来理解它:python文档(12)和StackOverflow(12)中的相关问题

我被困在这里了。有什么建议吗??欢迎回答!


Tags: topathintxtaswithlineopen
1条回答
网友
1楼 · 发布于 2024-04-28 11:43:44

如果不使用编码,那么使用codecs.open()是没有意义的。要么将codecs.open()一起使用为读写指定的编码,要么完全放弃它。没有编码,codecs.open()只是open()的别名。

在这里,您确实需要指定要打开的文件的编解码器,以处理Unicode值。当超出ASCII字符时,还应该使用unicode文本值;指定源文件编码或对数据使用unicode转义码:

# -*- coding: utf-8 -*- 
import os
import codecs

dirpath = u"C:\\Users\\user\\path\\to\\textfiles"
filenames = os.listdir(dirpath)

with codecs.open(r'C:\Users\user\path\to\output.txt', 'w', encoding='utf8') as outfile:
    for fname in filenames:
        currentfile = os.path.join(dirpath, fname)
        with codecs.open(currentfile, encoding='utf8') as infile:
            outfile.write(fname + '\n\n')
            for line in infile:
                line = line.replace(u"´ı", u"i")
                line = line.replace(u"ï¬", u"fi")
                line = line.replace(u"fl", u"fl")
                outfile.write (line)

这将指定给您使用UTF-8编解码器保存源文件的解释器,确保u"´ı"代码点正确解码为Unicode值,并在使用codec.open()打开文件时使用encoding确保您读取的行被解码为Unicode值,并确保您的Unicode值被写入输出文件为UTF-8。

注意,dirpath值是一个Unicode值以及。如果使用Unicode路径,则os.listdir()返回Unicode文件名,如果这些文件名中有任何非ASCII字符,则必须返回Unicode文件名。

如果不执行所有这些操作,则可能是源代码编码与从文件中读取的数据不匹配,并且试图用几个ASCII字符替换错误的编码字节集。

相关问题 更多 >