[英]Counting occurences in a Json with python
i managed to find a way to scrap discord messages from a specific channel, turn them into a json format and print the result.我设法找到了一种方法来从特定频道中删除 discord 消息,将它们转换为 json 格式并打印结果。
import requests
import json
def retrieve_messages(channelid):
headers = {
'authorization':'MjExMTQ1ODEzNTk2ODMxNzU2.YjtnkQ.-jOz1PucvMjdQ8r2yXdKMpSLK2M'
}
response = requests.get(
f'https://discord.com/api/v9/channels/{channelid}/messages', headers=headers)
data = json.loads(response.text)
for description in data:
print(description)
retrieve_messages('956262565237903401')
Which returns just fine what it's supposed to.哪个返回得很好。
EG: Cleared in 27:38 of 38:00 (27.3% remaining) for 148 Points\n\n Kindama - Healer (Holy Priest) EG:在 38:00 的 27:38(剩余 27.3%)获得 148 点数\n\n Kindama - Healer (Holy Priest)
The thing that i'd like to do and cannot find how to whatsoever, is, how can i count the occurences in all those lines of a particular keyword such as "Kindama"我想做但找不到方法的事情是,我如何计算特定关键字(例如“Kindama”)在所有这些行中的出现次数
I've tried syntax with.index which return false even if the string is present in json,我尝试了 with.index 语法,即使字符串存在于 json 中,它也会返回 false,
If anyone with python/json knowledge could give me hints about where to go from there i'd be thankful,如果有 python/json 知识的人可以给我提示从那里到 go 的位置,我将不胜感激,
EDIT, Tryouts:编辑,试用:
adding to the function:添加到 function:
index=data.index("Kindama")
print(index)
Tells me that 'Kindama' is not in list告诉我“Kindama”不在列表中
adding to the function:添加到 function:
for line in data:
for key in occurences.keys():
occurences[key] += line.count(key)
print(occurences)
Tells me that "AttributeError: 'dict' object has no attribute 'count'"告诉我“AttributeError: 'dict' object 没有属性 'count'”
So what i'm guessing at that point is that the scrapping didnt transform the data in a proper string or that i'm accessing it properly所以我当时猜测是报废没有将数据转换为正确的字符串或者我正在正确访问它
You can use a dictionary and string.count(substring)
, like so:您可以使用字典和string.count(substring)
,如下所示:
text = [
" Cleared in 27:38 of 38:00 (27.3% remaining) for 148 Points\n\n🛡 Kindama - Healer (Holy Priest)",
"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.",
"At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
"Lorem, ipsum, ipsum"
]
occurences = {
"Kindama" : 0,
"Lorem" : 0,
"ipsum" : 0,
"Nope" : 0
}
for line in text:
for key in occurences.keys():
occurences[key] += line.count(key)
print(occurences)
Result:结果:
{'Kindama': 1, 'Lorem': 3, 'ipsum': 4, 'Nope': 0}
Notice that the solution is case sensitive请注意,该解决方案区分大小写
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.