如何将API源字符串Unicode转换为UTF8

2024-09-28 01:31:35 发布

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

我无法将以下列表中的数据转换为UTF-8,我必须将其转换,以便使用pyodbc将其插入SQL表中:

cod_cat = ['Transfer\\u00eancia', 'Entrada de Transfer\\u00eancia', 'Sa\\u00edda de Transfer\\u00eancia']

当我在邮递员身上试用时,同样的数据:

cod_cat = ['Transferência', 'Entrada de Transferência','Saída de Transferência']

此列表来自使用以下代码的API请求:

res = requests.post(url, json=teste)
resposta = res.text

我使用了一个函数,该函数在请求-响应中查找特定的分隔符,并在每次出现这些分隔符时在它们之间添加字符串

我试图:

for i in lista_cat:
     i.decode('utf-8', 'ignore')

在库导入之前:

# -*- coding: utf-8 -*

我还尝试了encode(),然后再次解码,但是这三种方法都没有得到正确的结果,我试图找出哪种编码类型“res”能让我明白,但正如我在其他问题中发现的那样

Correctly detecting the encoding all times is impossible.

我的猜测是.text并不是获取这些特殊字符数据的最佳方法,但是我不知道其他方法

下面是res.text的示例:

"definida_pelo_usuario":"N","descricao":"Transfer\u00eancia","descricao_padrao":"Transfer\u00eancia"

我用来制作列表的函数:

resposta = res.text
def achar_str(inicio, delimitante):
    foo = resposta
    bar = inicio
    lista = []
    idx = 0
    ind = 0
    countador = 0
    while True:
        try:

            # find "foo"
            found_at = foo.index(bar, idx)
            achar = foo.index(delimitante, ind)

            # move the index to after "bar"
            idx = found_at + len(bar)
            ind = achar + len(produto)

            # append with strings between delimiters
            lista.append(res.text[found_at + len(bar):achar])
            # contador
            countador += 1

        except ValueError:
            return lista

Tags: 数据函数text列表foobarderes

热门问题