简体   繁体   English

如何从 python 的字段中提取特定数据进行打印?

[英]How do I extract a specific data from a Field in python to print it?

I'm using the discord.py API to build a bot to show me by different commands the results of some votes.我正在使用 discord.py API 构建一个机器人,通过不同的命令向我展示一些投票的结果。 For example, I have a question of Do you like fruit?例如,我有一个问题,你喜欢水果吗? And the options yes and no.和选项是和否。 I want to show by screen when you use the.votes command that the option 1 (yes) has 3 votes and the option 2 (no) has 1, The problem is that the variable that contains the number of votes is not an individual variable nor it gives it to me in JSON format.当您使用 .votes 命令时,我想通过屏幕显示选项 1(是)有 3 票,选项 2(否)有 1,问题是包含票数的变量不是单个变量它也没有以 JSON 格式给我。 but in Field format (any): This returns postman when I make the request:但在字段格式(任何):当我提出请求时,这将返回 postman :

"res": "OrderedDict([('option', 'Yes'), ('number', 2), ('votes', 3)), OrderedDict([('option', 'No'), ('number', 1), ('votes', 1))" "res": "OrderedDict([('option', 'Yes'), ('number', 2), ('votes', 3)), OrderedDict([('option', 'No'), (' number', 1), ('votes', 1))"

From this, I only want the command to use the 'votes' part, but I don't know how to extract it from the string.由此,我只希望命令使用“投票”部分,但我不知道如何从字符串中提取它。

I extracted the other data from the other fields like this:我从其他字段中提取了其他数据,如下所示:

data = v.json()[1]
voter = data['voter']

since they are JSONField.因为它们是 JSONField。 But I don't know how to do it with the other form.但我不知道如何使用另一种形式。

Could you please help me?请你帮助我好吗?

EDIT: I tried using this code I've seen in some questions here编辑:我尝试使用我在这里的一些问题中看到的这段代码

 for line in res.split('OrderedDict'):
        vote = re.match(".*'votes',(\d+)", line)
        print(vote.group(1))
 

but it doesn't work either.但它也不起作用。

Thank you in advance先感谢您

I'm not familiar with the discord API, but it looks like you've got a library returning an OrderedDict() .我不熟悉 discord API,但看起来你有一个返回OrderedDict()的库。 You should be able to treat this more or less equivalently to a normal Python dict, and retrieve values by key:您应该能够或多或少地将其视为普通的 Python dict,并通过键检索值:

from collections import OrderedDict
choice = OrderedDict([('option', 'Yes'), ('number', 2), ('votes', 3)]) 
n_votes = choice['votes']
print(n_votes)
# 3

By the way, the example you've posted is broken somehow.顺便说一句,您发布的示例以某种方式损坏。 The brackets are not balanced - could be a faulty copy-paste.括号不平衡 - 可能是错误的复制粘贴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM