【问题标题】:Decoding string in python3python3中的解码字符串
【发布时间】:2021-11-30 10:43:24
【问题描述】:

如何转换

str1 = 'Sabrau00AE Family Size Roasted Pine Nut Hummus - 17 oz' 

final_str = 'Sabra® Family Size Roasted Pine Nut Hummus - 17oz'` in python3.

我试过了:

  1. str1.encode('utf-8') html.unescape
  2. str1.encode('utf-8').decode('unicode_escape')
  3. str1.encode('utf-8').decode('ascii')

但没有运气。

isinstance(str1,str) 的输出是True str1.encode('utf=8') 的输出是字节字符串 b'Sabrau00AE Family Size Roasted Pine Nut Hummus - 17 oz'

我也导入了charade,但是编码和解码功能出错。

AttributeError: 'str' object has no attribute 'decode'  
AttributeError: 'str' object has no attribute 'encoding'

【问题讨论】:

    标签: python utf-8 ascii decode encode


    【解决方案1】:

    感谢@Mark Tolonen 对正则表达式的帮助。在您的输出中,我在名称中也得到了“u”以及解码的符号。因此,我使用以下代码修复了边缘情况

    1. 查找旁边带有 'u' 和 4 个数字/字符的子字符串。
    2. 使用替换函数将此子字符串转换为 Unicode 字符串
    3. 使用 Unicode 转义解码

    以下代码有效:

    def convert(s):
        # return re.sub(r'[0-9A-F]{4}',lambda m: chr(int(m.group(),16)), s)
        return str.encode(re.sub(r'u[0-9A-F]{4}',lambda m:(m.group().replace('u','\\u')),s),'utf-8').decode('unicode-escape')
    

    输入:

     str1 = 'Sabrau00AE Family Size Roasted Pine Nut Hummus - 17 oz'
    

    代码:

    str2=convert(str1)
    print (str2)
    print(type(str2))
    

    输出:

    Sabra® Family Size Roasted Pine Nut Hummus - 17 oz
    <class 'str'>
    

    【讨论】:

      【解决方案2】:

      您的字符串没有标准编码,可能不明确。假设任何时候“连续四个十六进制数字”表示“插入 Unicode 代码点”,那么下面的工作,但注意 any u 与 4 位将转换为 Unicode 字符,例如“Plateau1000 蛋白粉”将变为“Plateaက 蛋白粉”:

      import re
      
      # 1. locate u followed by 4 hexdigits
      # 2. capture digits and convert to an integer using base 16
      # 3. convert integer to a Unicode char
      # 4. use character as the substitution for the digits
      def convert(s):
          return re.sub(r'u([0-9A-F]{4})',lambda m: chr(int(m.group(1),16)), s)
      
      str1 = 'Sabrau00AE Family Size Roasted Pine Nut Hummus - 17 oz'
      str2 = convert(str1)
      print(str2)
      

      输出:

      Sabra® Family Size Roasted Pine Nut Hummus - 17 oz
      

      【讨论】:

      • 这行得通,但让你和符号一起。即您的输出:Sabra® Family Size 烤松子鹰嘴豆泥 - 17 盎司 所需输出:Sabra® Family Size 烤松子鹰嘴豆泥 - 17 盎司。我已经在下面的回答中解决了这个问题。谢谢。
      • @Shivangi._k 啊,没有发现 u 是转义码的一部分,因此我的评论是模棱两可。编辑答案。
      【解决方案3】:

      您正在寻找\u;使用它在代码点之前,它将呈现正确的 unicode 字符。

      >>> str1 = 'Sabrau\u00AE Family Size Roasted Pine Nut Hummus - 17 oz'
      >>> str1
      'Sabrau® Family Size Roasted Pine Nut Hummus - 17 oz'
      

      【讨论】:

      • 这在字符串中有 \u 时有效。但是我们得到的字符串没有\u。 str1 = 'Sabrau00AE Family Size Roasted Pine Nut Hummus - 17 oz' 如何将其转换为 'Sabrau\u00AE Family Size Roasted Pine Nut Hummus - 17 oz' 以便应用最终操作。
      • OP 已经有一个没有 \u 转义码的字符串。 \u 转义仅在源代码中创建字符串文字时起作用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多