【问题标题】:UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 7240: character maps to <undefined>UnicodeDecodeError:“charmap”编解码器无法解码位置 7240 中的字节 0x8d:字符映射到 <undefined>
【发布时间】:2015-08-16 09:06:33
【问题描述】:

我是正在做硕士论文的学生。作为我论文的一部分,我正在使用 python。我正在读取.csv 格式的日志文件,并将提取的数据以格式良好的方式写入另一个.csv 文件。但是,当读取文件时,我收到此错误:

Traceback(最近一次调用最后一次):文件 “C:\Users\SGADI\workspace\DAB_Trace\my_code\trace_parcer.py”,第 19 行, 在阅读器中的行中:

  • 文件 "C:\Users\SGADI\Desktop\Python-32bit-3.4.3.2\python-3.4.3\lib\encodings\cp1252.py", 第 23 行,在解码中返回 codecs.charmap_decode(input,self.errors,decoding_table)[0]
  • UnicodeDecodeError:“charmap”编解码器无法解码位置 7240 中的字节 0x8d:字符映射到 &lt;undefined&gt;
import csv
import re
#import matplotlib
#import matplotlib.pyplot as plt
import datetime
#import pandas
#from dateutil.parser import parse
#def parse_csv_file():
timestamp = datetime.datetime.strptime('00:00:00.000', '%H:%M:%S.%f')
timestamp_list = []
snr_list = []
freq_list = []
rssi_list = []
dab_present_list = []
counter = 0
f =  open("output.txt","w")
with open('test_log_20150325_gps.csv') as csvfile:
    reader = csv.reader(csvfile, delimiter=';') 
    for row in reader:
        #timestamp = datetime.datetime.strptime(row[0], '%M:%S.%f')
        #timestamp.split(" ",1)

        timestamp = row[0]
        timestamp_list.append(timestamp)


        #timestamp = row[0]
        details = row[-1]
        counter += 1
        print (counter)
        #if(counter > 25000):
        #  break
        #timestamp = datetime.datetime.strptime(row[0], '%M:%S.%f')  



        #timestamp_list.append(float(timestamp))

        #search for SNRLevel=\d+
        snr = re.findall('SNRLevel=(\d+)', details)
        if snr == []:
            snr = 0
        else:
            snr = snr[0]
        snr_list.append(int(snr))

        #search for Frequency=09ABC
        freq = re.findall('Frequency=([0-9a-fA-F]+)', details)
        if freq == []:
            freq = 0
        else:
            freq = int(freq[0], 16)
        freq_list.append(int(freq))

        #search for RSSI=\d+
        rssi = re.findall('RSSI=(\d+)', details)
        if rssi == []:
            rssi = 0
        else:
            rssi = rssi[0]
        rssi_list.append(int(rssi))

        #search for DABSignalPresent=\d+
        dab_present = re.findall('DABSignalPresent=(\d+)', details)
        if dab_present== []:
            dab_present = 0
        else:
            dab_present = dab_present[0]
        dab_present_list.append(int(dab_present))

        f.write(str(timestamp) + "\t")
        f.write(str(freq) + "\t")
        f.write(str(snr) + "\t")
        f.write(str(rssi) + "\t")
        f.write(str(dab_present) + "\n")
        print (timestamp, freq, snr, rssi, dab_present)

        #print (index+1)

        #print(timestamp,freq,snr)
        #print (counter)
#print(timestamp_list,freq_list,snr_list,rssi_list)


'''if  snr != []:
           if freq != []:
               timestamp_list.append(timestamp)
               snr_list.append(snr)
               freq_list.append(freq)
f.write(str(timestamp_list) + "\t")
f.write(str(freq_list) + "\t")
f.write(str(snr_list) + "\n")

print(timestamp_list,freq_list,snr_list)'''
f.close()

我搜索了特殊字符,但没有找到。我搜索了建议更改格式的互联网:我尝试了 ut8、latin1 和其他一些格式,但我仍然收到此错误。你能帮我解决一下pandas吗?我也尝试使用pandas,但我仍然收到错误消息。 我什至在日志文件中删除了一行,但错误出现在下一行。

请帮我找到解决办法,谢谢。

【问题讨论】:

  • 请发帖repr(open('test_log_20150325_gps.csv', 'rb').read(7290)[7190:])。这将向我们展示 CSV 文件中第 7240 个字节附近的一些内容。使用它我们可能能够猜测什么是可能的编解码器。
  • 当我发布上述命令时,我在控制台中得到了这个 b'XPMSG_OPCODE_SET_CONTROL_FLAGS_CMD;;;;;;;;;RR=2 OP=DAB_NXPMSG_OPCODE_SET_CONTROL_FLAGS_CMD CAVisibil'
  • 这里有些不一致,因为您发布的repr 中没有字节'\x8d'。可以发test_log_20150325_gps.csv吗?
  • 这里是文件drive.google.com/…的链接

标签: csv python-3.x pandas decode python-import


【解决方案1】:

我已经解决了这个问题。 我们可以使用这段代码

import codecs
types_of_encoding = ["utf8", "cp1252"]
for encoding_type in types_of_encoding:
    with codecs.open(filename, encoding = encoding_type, errors ='replace') as csvfile:
        your code
        ....
        ....

【讨论】:

    【解决方案2】:

    我已经通过简单地在 open() 中添加一个参数解决了这个问题

    with open(filename, encoding = 'cp850') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
    

    【讨论】:

      【解决方案3】:
      with open('input.tsv','rb') as f:
      for ln in f:
          decoded=False
          line=''
          for cp in ('cp1252', 'cp850','utf-8','utf8'):
              try:
                  line = ln.decode(cp)
                  decoded=True
                  break
              except UnicodeDecodeError:
                  pass
          if decoded:
              # use 'line'
      

      【讨论】:

        猜你喜欢
        • 2019-05-14
        • 1970-01-01
        • 2020-04-14
        • 2022-06-13
        • 2019-06-01
        • 1970-01-01
        • 2019-10-20
        • 2017-02-06
        相关资源
        最近更新 更多