将 UTF-16 转换为 UTF-8 并删除 BOM?

2024-04-19

我们有一位数据输入人员在 Windows 上使用 UTF-16 编码,希望使用 utf-8 并删除 BOM。 utf-8 转换有效,但 BOM 仍然存在。我该如何删除这个?这就是我目前所拥有的:

batch_3={'src':'/Users/jt/src','dest':'/Users/jt/dest/'}
batches=[batch_3]

for b in batches:
  s_files=os.listdir(b['src'])
  for file_name in s_files:
    ff_name = os.path.join(b['src'], file_name)  
    if (os.path.isfile(ff_name) and ff_name.endswith('.json')):
      print ff_name
      target_file_name=os.path.join(b['dest'], file_name)
      BLOCKSIZE = 1048576
      with codecs.open(ff_name, "r", "utf-16-le") as source_file:
        with codecs.open(target_file_name, "w+", "utf-8") as target_file:
          while True:
            contents = source_file.read(BLOCKSIZE)
            if not contents:
              break
            target_file.write(contents)

如果我 hexdump -C 我看到:

Wed Jan 11$ hexdump -C svy-m-317.json 
00000000  ef bb bf 7b 0d 0a 20 20  20 20 22 6e 61 6d 65 22  |...{..    "name"|
00000010  3a 22 53 61 76 6f 72 79  20 4d 61 6c 69 62 75 2d  |:"Savory Malibu-|

在生成的文件中。如何删除 BOM?

thx


这就是之间的区别UTF-16LE and UTF-16

  • UTF-16LE是小尾数without a BOM
  • UTF-16是大端还是小端with a BOM

所以当你使用UTF-16LE,BOM只是文本的一部分。使用UTF-16相反,BOM 会被自动删除。原因UTF-16LE and UTF-16BE存在的目的是让人们可以携带“正确编码”的文本而无需 BOM,但这不适用于您。

请注意当您使用一种编码进行编码并使用另一种编码进行解码时会发生什么。 (UTF-16自动检测UTF-16LE有时,但并不总是。)

>>> u'Hello, world'.encode('UTF-16LE')
'H\x00e\x00l\x00l\x00o\x00,\x00 \x00w\x00o\x00r\x00l\x00d\x00'
>>> u'Hello, world'.encode('UTF-16')
'\xff\xfeH\x00e\x00l\x00l\x00o\x00,\x00 \x00w\x00o\x00r\x00l\x00d\x00'
 ^^^^^^^^ (BOM)

>>> u'Hello, world'.encode('UTF-16LE').decode('UTF-16')
u'Hello, world'
>>> u'Hello, world'.encode('UTF-16').decode('UTF-16LE')
u'\ufeffHello, world'
    ^^^^ (BOM)

或者您可以在 shell 中执行此操作:

for x in * ; do iconv -f UTF-16 -t UTF-8 <"$x" | dos2unix >"$x.tmp" && mv "$x.tmp" "$x"; done
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 UTF-16 转换为 UTF-8 并删除 BOM? 的相关文章

随机推荐