在python中读取json文件时出现表情符号问题

2024-06-28 20:20:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个json文件,其中的字符串包含emojis

{
   "messages": "This is a test 📑-bla-bla test."
}

我的python代码是:

with open('config.json', 'r') as config_file:
    config = json.load(config_file)
print(config["messages"])

输出为:

This is a test 📑-bla-bla test.

如何解决这个表情符号编码问题


Tags: 文件字符串代码testconfigjsonisas
2条回答

您需要的是确保使用正确的编码保存/读取文件

with open('config.json', 'r', encoding='utf-8') as config_file: 
    config = json.load(config_file)
print(config["messages"])

您可以使用unidecode库。首先在终端内进行快速pip安装:

pip install unidecode

然后可以使用以下代码:

import unicodedata
from unidecode import unidecode


def deEmojify(inputString):
    returnString = ""

    for character in inputString:
        try:
            character.encode("ascii")
            returnString += character
        except UnicodeEncodeError:
            replaced = unidecode(str(character))
            if replaced != '':
                returnString += replaced
            else:
                try:
                     returnString += "[" + unicodedata.name(character) + "]"
                except ValueError:
                     returnString += "[x]"

    return returnString



string = '🙁😠hello😡😞😟😣__emoji😖','🙁😠___free😡😞___world😟😣😖'

print(deEmojify(string))

输出

hello__emoji___free___world

我希望我能帮你一点忙。:)

相关问题 更多 >