【问题标题】:How to get value from set with key containing a single quote loaded with YAML?如何使用包含用 YAML 加载的单引号的键从集合中获取值?
【发布时间】:2020-07-14 08:08:04
【问题描述】:

找不到关于这个问题的任何材料。

我有一个 yaml 文件,其中包含:

items :
- "jeweller's orb"

然后我加载它:

with open('./configs/items.yaml') as f:
    data = yaml.safe_load(f)
self.item_set = set([x.upper() for x in data['items']])

现在如何使用包含单引号的键访问集合? 我试过转义它,双引号,没有任何效果......

print('JEWELLER\’S ORB' in self.item_set)
print("JEWELLER\’S ORB" in self.item_set)
print('JEWELLER’S ORB' in self.item_set)
print("JEWELLER’S ORB" in self.item_set)
print(r'JEWELLER’S ORB' in self.item_set)
print(r"JEWELLER’S ORB" in self.item_set)

它们都返回 false。我不知道幕后有 yaml 的东西??

我还尝试复制 self.item_set 中变量的输出并直接在打印中使用它。还是什么都没有。

编辑: 答案是

with open('./configs/items.yaml', 'rt', encoding='utf8') as f:

以及在 yaml 中使用开头的单引号版本而不是直接单引号。哇,好痛。

【问题讨论】:

  • 试试"JEWELLER'S ORB"
  • 另请注意,您在代码中使用的单引号与yaml文件中的不同。
  • "JEWELLER'S ORB" in item_set
  • 一些(富文本)编辑器使用 unicode 引号而不是 vanilla ascii 引号。当您在 python 中比较它们时,它们是不相等的(不同的 unicode 代码点)。只需查看您问题中的第一次尝试即可。这些字符的呈现方式不同。

标签: python yaml


【解决方案1】:
with open('./configs/items.yaml', 'rt', encoding='utf8') as f:

以及在 yaml 中使用开头的单引号版本而不是直接单引号。哇,好痛。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    相关资源
    最近更新 更多