【问题标题】:How to decode a messed up UTF-8 string properly?如何正确解码混乱的 UTF-8 字符串?
【发布时间】:2013-10-02 13:32:10
【问题描述】:

我正在尝试使用 python 和 pyexiv2 读取 IPTC 数据。

import pyexiv2
image = pyexiv2.Image('test.jpg')
image.readMetadata()
print image['Iptc.Application2.Caption']

这给了我以下信息:

Copyright: Michael Huebner, Kontakt: +4915100000000xxxxxx Höxx (30) ist im Streit mit dem Arbeitsamt in Brandenburg, xxxxxxxxxxxxxx , xxxxxx,

但它应该给我:

Kinder: Axxxxx Hxxxxx (10) und Exxxxxx Höxx (5), Rxxxxxxx Höxx (30) ist im Streit mit dem Arbeitsamt in Brandenburg, xxxxxxxxxxxxx , xxxxxxxxxxx, 
Copyright: Michael Huebner, Kontakt: +4915100000000

有点乱,因为我必须删除个人数据,但你可以看到发生了什么:“换行符”使最后一部分覆盖字符串的第一部分。

但现在变得很奇怪:

for i in str(image['Iptc.Application2.Caption']):
  print i,

这只是以正确的顺序打印出所有字符,包括换行符。但它弄乱了“元音变音”字符。

这个:

unicode(image['Iptc.Application2.Caption'])

给我:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 41: ordinal not in range(128)

那么我怎样才能同时拥有:元音变音和正确的字符串顺序?如何修复这个字符串?

【问题讨论】:

  • 如果您需要在输出中包含换行符,请不要使用块引用。
  • print repr(image['Iptc.Application2.Caption']) 在字符串中显示什么?你可能有一个\r,一个回车。
  • 是的,它是\r。我该如何解决这个问题?

标签: python string utf-8 exif iptc


【解决方案1】:

您的数据使用了与您预期不同的行分隔符约定。这不是 UTF-8 特有的问题,真的。

您可以使用str.splitlines() 拆分行;它会将\r 识别为行分隔符。或者,您可以使用\n重新加入您的线路:

>>> sample = 'line 1\rline 2'
>>> print sample
line 2
>>> sample.splitlines()
['line 1', 'line 2']
>>> print '\n'.join(sample.splitlines())
line 1
line 2

【讨论】:

    猜你喜欢
    • 2017-06-02
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 2019-12-13
    • 2019-09-15
    相关资源
    最近更新 更多