从文本文件编码表情符号(Python)的最佳和干净的方法

问题描述 投票:0回答:2

参考这个问题:Emoji 上传到 Big Query 时崩溃

我正在寻找最好、最干净的方法来将表情符号从这个

\ud83d\ude04
类型编码到这个(Unicode) -
\U0001f604
因为目前,除了创建将通过文本文件传递的 python 方法之外,我没有任何想法并替换表情符号编码。

这是可以转换的字符串:

在 python 3 中将表情符号转换为 Unicode,反之亦然

作为假设,也许需要逐行传递文本并进行转换??

潜在想法:

with open(ff_name, 'rb') as source_file:
  with open(target_file_name, 'w+b') as dest_file:
    contents = source_file.read()
    dest_file.write(contents.decode('utf-16').encode('utf-8'))
python unicode text-files encode emoji
2个回答
9
投票

因此,我假设您以某种方式获得了一个原始 ASCII 字符串,其中包含带有形成代理项对的 UTF-16 代码单元的转义序列,并且您(无论出于何种原因)想要将其转换为

\UXXXXXXXX
格式。

因此,从今以后我假设您的输入(字节!)如下所示:

weirdInput = "hello \\ud83d\\ude04".encode("latin_1")

现在您想要执行以下操作:

  1. 以将
    \uXXXX
    事物转换为 UTF-16 代码单元的方式解释字节。有
    raw_unicode_escapes
    ,但不幸的是它需要单独的pass来修复代理对(说实话,我不知道为什么)
  2. 修复代理对,将数据转换为有效的UTF-16
  3. 解码为有效的 UTF-16
  4. 再次编码为“raw_unicode_escape”
  5. 解码回旧版
    latin_1
    ,仅由旧版 ASCII 和格式为
    \UXXXXXXXX
    的 Unicode 转义序列组成。

类似这样的:

  output = (weirdInput
    .decode("raw_unicode_escape")
    .encode('utf-16', 'surrogatepass')
    .decode('utf-16')
    .encode("raw_unicode_escape")
    .decode("latin_1")
  )

现在如果你

print(output)
,你会得到:

hello \U0001f604

请注意,如果您在中间阶段停止:

smiley = (weirdInput
  .decode("raw_unicode_escape")
  .encode('utf-16', 'surrogatepass')
  .decode('utf-16')
)

然后你会得到一个带有笑脸的 Unicode 字符串:

print(smiley)
# hello 😄

完整代码:

weirdInput = "hello \\ud83d\\ude04".encode("latin_1")

output = (weirdInput
  .decode("raw_unicode_escape")
  .encode('utf-16', 'surrogatepass')
  .decode('utf-16')
  .encode("raw_unicode_escape")
  .decode("latin_1")
)


smiley = (weirdInput
  .decode("raw_unicode_escape")
  .encode('utf-16', 'surrogatepass')
  .decode('utf-16')
)

print(output)
# hello \U0001f604

print(smiley)
# hello 😄

0
投票

\ud83d\ude04
是字符的 utf16 表示
SMILING FACE WITH OPEN MOUTH AND SMILING EYES (U+1F604)
您需要将其解码为字符,然后将字符的代码点转换为十六进制字符串。我对 Python 的了解不够,无法告诉你如何做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.