从文本文件中在冒号之后或冒号之前获取值 [英] getting the value from text file after the colon or before the colon in python
问题描述
我只需要最后一个数字25,所以我可以将其更改为int().我有这个文本文件:
I only need the last number 25 so i can change it to int(). I have this text file:
{
"members": [
{"name": "John", "location": "QC", "age": 25},
{"name": "Jesse", "location": "PQ", "age": 24},
}
然后返回年龄的值
到目前为止,我一直在尝试这种方法,因此很困扰……我使用哪种函数来解析它?那就是你所说的吗?我是编程和python的新手.
This what I have tried so far, so I am so stuck... What kind of function do I use to parse it? Is that what you call it? I'm new to programming and in python.
import json
import pprint
my_data = json.loads(open("team.json.txt").read())
print 'members whose location is in PQ'
member_in_pq = [member for member in my_data['members'] \
if member['location'] == 'PQ']
pprint.pprint(member_in_pq)
通过我尝试这段代码的方式,它给出了一个错误:
By the way I tried this code but it gives an error:
result = my_data.split(':')[-1]
推荐答案
我不确定您要问怎么做,但会尝试猜测.
I'm not sure what you're asking how to do, but will make an attempt to guess.
首先,您显示的文本不是有效的JSON,需要将其更改为以下内容:
First of all, the text you show isn't valid JSON and would need to be changed to something like this:
{
"members": [
{"name": "John", "location": "QC", "age": 25},
{"name": "Jesse", "location": "PQ", "age": 24}
]
}
这里可以打印出位置PQ
中每个成员的所有数据:
Here's something that would print out all the data for each member in location PQ
:
import json
import pprint
my_data = json.loads(open("team.json.txt").read())
members_in_pq = [member for member in my_data['members']
if member['location'] == 'PQ']
print 'members whose location is in PQ'
for member in members_in_pq:
print ' name: {name}, location: {location}, age: {age}'.format(**member)
输出:
members whose location is in PQ
name: Jesse, location: PQ, age: 24
这篇关于从文本文件中在冒号之后或冒号之前获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!