5 python unicode encode text-files emoji
提到这个问题: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'))
Run Code Online (Sandbox Code Playgroud)
因此,我假设您以某种方式获得了一个原始 ASCII 字符串,其中包含带有形成代理项对的 UTF-16 代码单元的转义序列,并且您(无论出于何种原因)希望将其转换为 -\UXXXXXXXX格式。
因此,今后我假设您的输入(字节!)如下所示:
weirdInput = "hello \\ud83d\\ude04".encode("latin_1")
Run Code Online (Sandbox Code Playgroud)
现在您想要执行以下操作:
\uXXXX以将事物转换为 UTF-16 代码单元的方式解释字节。有raw_unicode_escapes,但不幸的是它需要单独的传递来修复代理对(说实话,我不知道为什么)latin_1,仅由旧版 ASCII 和 Unicode 转义序列组成\UXXXXXXXX。像这样的东西:
output = (weirdInput
.decode("raw_unicode_escape")
.encode('utf-16', 'surrogatepass')
.decode('utf-16')
.encode("raw_unicode_escape")
.decode("latin_1")
)
Run Code Online (Sandbox Code Playgroud)
现在如果你print(output),你会得到:
hello \U0001f604
Run Code Online (Sandbox Code Playgroud)
请注意,如果您在中间阶段停止:
smiley = (weirdInput
.decode("raw_unicode_escape")
.encode('utf-16', 'surrogatepass')
.decode('utf-16')
)
Run Code Online (Sandbox Code Playgroud)
然后你会得到一个带有笑脸的 Unicode 字符串:
print(smiley)
# hello
Run Code Online (Sandbox Code Playgroud)
完整代码:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16142 次 |
| 最近记录: |