<feff> 问题

之前多次遇到在文件头中看到<feff>的情况,都会导致数据有问题。开始只是删除它没太注意是怎么回事,这次又遇到了这个问题,查了一下,总结了一下问题。分享一下。

 UTF-8编码中BOM的检测与删除

先解释一个名词BOM,所谓BOM,全称是Byte Order Mark,它是一个Unicode字符,通常出现在文本的开头,用来标识字节序 (Big/LittleEndian),除此以外还可以标识编码(UTF-8/16/32),如果出现在文本中间,则解释为zero width no-breakspace

注:Unicode相关知识的详细介绍请参考UTF-8, UTF-16, UTF-32 & BOM

对于UTF-8/16/32而言,它们名字中的8/16/32指的是编码单位是多少位的,也就是说,它们的编码单位分别是8/16/32位,换算成字节就是1/2/4字节,如果是多字节,就要牵扯到字节序,UTF-8以单字节为编码单位,所以不存在字节序。

八进制的BOM:357、273、277,十六进制的BOM:EF、BB、BF,


在windows下保存文件编码为UTF-8会在文件头加上BOM,所以我们在读文件时会出现报错。在linux下用vim打开会看到<feff>,就是这个问题。

linux下

如何检测UTF-8编码中的BOM呢?

shell> grep -I-r -l $'\xEF\xBB\xBF' /path

如何删除UTF-8编码中的BOM呢?

shell> grep -I-r -l $'\xEF\xBB\xBF' /path | xargs sed -i 's/^\xEF\xBB\xBF//;q'


windows下把文件用记事本打开另存为ANSI就可以了。



可以使用Python中的pandas库来将XML数据转化为Excel格式,以下是示例代码: ```python import pandas as pd from xml.etree import ElementTree # 读取XML数据 xml_data = '''<?xml version="1.0" encoding="UTF-8"?> <list> <item> <userId>3f2bc360-adc1-4adf-bbd9-092939603af8</userId> <eid>xuyang</eid> <displayName>yang xu</displayName> <type>registered</type> </item> <item> <userId>5d7713fd-8133-40a8-94ad-3a145ed44df8</userId> <eid>yisirui</eid> <displayName>sirui yi</displayName> <type>registered</type> </item> <item> <userId>5dcaf2c0-fb7c-47fe-99bc-df21ede9011b</userId> <eid>xiaosun</eid> <displayName>xuyang sun</displayName> <type>registered</type> </item> <item> <userId>7ea060ff-d6e4-4552-9682-6483eb692a8f</userId> <eid>alex</eid> <displayName>alex Yu</displayName> <type>registered</type> </item> <item> <userId>e190e122-96ef-4b43-9b9e-11a08400c87f</userId> <eid>wanglinkai</eid> <displayName>cui xiai</displayName> <type>registered</type> </item> <item> <userId>e3d6d07e-7a34-47c0-969f-9401ddeab675</userId> <eid>cuikairui</eid> <displayName>kairui cui</displayName> <type>registered</type> </item> <item> <userId>f304a0e1-e0a9-4518-9099-4ef5c2cdb22f</userId> <eid>xuchenxi</eid> <displayName>chenxi xu</displayName> <type>registered</type> </item> </list>''' root = ElementTree.fromstring(xml_data) # 将XML数据转化为DataFrame data = [] for item in root.findall('item'): userId = item.find('userId').text eid = item.find('eid').text displayName = item.find('displayName').text type_ = item.find('type').text data.append([userId, eid, displayName, type_]) df = pd.DataFrame(data, columns=['userId', 'eid', 'displayName', 'type']) # 将DataFrame保存为Excel文件 df.to_excel('data.xlsx', index=False) ``` 运行该代码后,会在当前目录下生成一个名为"data.xlsx"的Excel文件,其中包含了XML数据中的各个字段。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值