用一行中的某个字符串过滤文本文件,然后返回该行中的另一个字符串 [英] filtering a text file with a certain string in a line then returning another string within the line

查看:205
本文介绍了用一行中的某个字符串过滤文本文件,然后返回该行中的另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的文本文件名为team.json
我的问题是,我只知道如何返回特定的行,
例如,我选择一个过滤器的位置,像PQ我将如何返回名称有PQ位置。感谢提前。

  {
members:[
{name:John ,位置:QC,年龄:25},
{name:Jesse,location:PQ,age:24},
{名称:Jez,location:PQ,age:23},
{name:Ry,location:PQ,age:22},
{name:Barry,location:PQ,age:25},
{name:Rikki,location:PQ年龄:35},
{name:Ross,location:PQ,age:33},
{name:Chiz :PQ,age:25},
{name:Gel,location:PQ,age:24},
{name Cherry,location:PQ,age:22}
]
}

这是我的代码,但只返回行

  import json 
my_data = json.loads (打开(team.json.txt)。read())

打开my_data

打开('team.json.txt'):
ifJohnin:
print line


解决方案

一旦你已经解析了你的json数据,你可以用这个来提取PQ位置的成员:
$ b $ pre $ member $成员的成员在my_data ['members'] \
if member ['location'] =='PQ']
print(member_in_pq)
# - > [{'age':24,'location':'PQ','name':'Jesse'},...]

或者,如果您只想要名称:

  member_in_pq = [member ['name']成员'] \ 
if member ['location'] =='PQ']
print(member_in_pq)
# - > ['Jesse','Jez',...,'Cherry']

我推荐使用您的数据的解析版本,而不是手动返回和解析文件(再次)。

this is my text file named team.json my problem is that I only know how to return a specific line, For example i select a filter location, like PQ how would i return the names that has a PQ location. thanks in advance.

{
  "members": [
    {"name": "John", "location": "QC", "age": 25},
    {"name": "Jesse", "location": "PQ", "age": 24},
    {"name": "Jez", "location": "PQ", "age": 23},
    {"name": "Ry", "location": "PQ", "age": 22},
    {"name": "Barry", "location": "PQ", "age": 25},
    {"name": "Rikki", "location": "PQ", "age": 35},
    {"name": "Ross", "location": "PQ", "age": 33},
    {"name": "Chiz", "location": "PQ", "age": 25},
    {"name": "Gel", "location": "PQ", "age": 24},
    {"name": "Cherry", "location": "PQ", "age": 22}
  ]
}

this is my code but only returns the line

import json
my_data = json.loads(open("team.json.txt").read())

print my_data

for line in open('team.json.txt'):
 if "John" in line:
  print line

解决方案

once you have parsed your json data you could use this to extract members in the PQ location:

member_in_pq = [member for member in my_data['members'] \
    if member['location'] == 'PQ']
print(member_in_pq)
# -> [{'age': 24, 'location': 'PQ', 'name': 'Jesse'}, ...]

or, if you want just the names:

member_in_pq = [member['name'] for member in my_data['members'] \
    if member['location'] == 'PQ']
print(member_in_pq)
# -> ['Jesse', 'Jez',..., 'Cherry']

i recommend using the parsed version of your data instead of going back and parsing the file (again) manually.

这篇关于用一行中的某个字符串过滤文本文件,然后返回该行中的另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆