【问题标题】:Given a key value string values, how to encode a key and not the content (Python 3) [closed]给定键值字符串值,如何编码键而不是内容(Python 3)[关闭]
【发布时间】:2017-10-15 04:35:57
【问题描述】:

给定一个键:值(name="My name is Bill"),在 Python 3 中,我正在尝试对键(即名称)进行编码。像 name.encode 等标准方法最终会对内容进行编码。下一步需要将其编码为字节

【问题讨论】:

  • 听起来您正在尝试对变量名称进行编码。首先,为什么?其次,如果您确实设法对变量名称进行编码,那么您最终会得到一个不同的变量名称——您不会更改现有的变量名称。您谈论更改密钥,但密钥不是变量名,并且根据定义是不可变的。
  • 这个变量(键)保存一个值,它进入一个张量。张量中的构造使用具有相同名称的键和值。现在,必须将密钥编码为字节,否则会出现不兼容问题。

标签: python tensorflow python-3.5 encode


【解决方案1】:
#!/usr/bin/python
import codecs

def encoder(obj, scheme, orig_scheme):
    # A function which will perform encoding and return encoded object
    temp_obj = {}
    for k in obj:
        new_key = codecs.encode(bytes(k, orig_scheme), scheme).strip().decode(orig_scheme)
        temp_obj[new_key] = obj[k]
    return temp_obj

dict_usr_obj = {
    "name": "Usr X",
    "age": 23,
    "gender": "Male"
}
encoded_obj = encoder(dict_usr_obj, "base64", "utf-8")
print (encoded_obj)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    相关资源
    最近更新 更多