Lunatic Fnatic
Lunatic Fnatic

Reputation: 681

Search for a text in text file stored as array

I have a text file where my data is stored as arrays;

Example:

{'id': '1', 'name': 'a', 'color': 'red'}
{'id': '2', 'name': 'b', 'color': 'blue'}
{'id': '3', 'name': 'c', 'color': 'yellow'}
{'id': '4', 'name': 'd', 'color': 'purple'}

I want to search specific values in this text file and print out the whole matching line info. For instance i want to search color where the color is purple I want to print out the whole line.

I tried to use nmap but it didn't help.

f = open('dbtest.txt')
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('purple') != -1:
    print 'I_DK_HOW_TO_PRINT_THIS_LINE'

Can anyone tell me the easiest way of doing this?

Edit: When I select search based on name, I only want to search values in 'name'

Upvotes: 0

Views: 56

Answers (2)

TLOwater
TLOwater

Reputation: 638

with open("hello.txt", 'r') as input_file:
    for row in input_file:
        dict_this_row = (eval(row))
        if dict_this_row["color"] == 'purple' and "color" in dict_this_row:
            print(dict_this_row)

This loads the values as a dictionary which you can then call with the key. From this you can either create a composite dictionary (writing to a master dictionary based on keys for each row) or you can search for the value as you go.

Edited to match the style of the Laurent's answer.

Upvotes: 0

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22952

I make the asumption that each line of your text file contains JSON data:

import textwrap  # to have indented string here...

content = textwrap.dedent("""\
{'id': '1', 'name': 'a', 'color': 'red'}
{'id': '2', 'name': 'b', 'color': 'blue'}
{'id': '3', 'name': 'c', 'color': 'yellow'}
{'id': '4', 'name': 'd', 'color': 'purple'}
""")

import io
import json

with io.StringIO(content) as f:
    for line in f:
        # JSON parser don't support simple quoted-strings
        line = line.replace("'", '"')
        data = json.loads(line)
        if 'color' in data and data['color'] == 'purple':
            print(data)

You get:

{'name': 'd', 'color': 'purple', 'id': '4'}

For a classic file, you can write:

with open('dbtest.txt') as f:
    for line in f:
        line = line.replace("'", '"')
        data = json.loads(line)
        if 'color' in data and data['color'] == 'purple':
            print(data)

You can also store your "records" in a list for future use:

records = []
with open('dbtest.txt') as f:
    for line in f:
        line = line.replace("'", '"')
        records.append(json.loads(line))

selection = [record for record in records
             if 'color' in record and record['color'] == 'purple']

print(selection)

You get:

[{'name': 'd', 'color': 'purple', 'id': '4'}]

Upvotes: 1

Related Questions