2017-04-25 96 views
0

我有一个文本文件,其中的数据以数组形式存储;搜索存储为数组的文本文件中的文本

例子:

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

我要搜索特定的值,在这个文本文件并打印出整个匹配行信息。例如,我想搜索颜色是紫色的地方,我想打印出整行。

我试图使用nmap,但它没有帮助。

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' 

有谁能告诉我这样做的最简单方法吗?

编辑:当我选择搜索基础上的名字,我只希望在'name'

回答

1

我做你的文本文件的每一行包含JSON数据asumption:

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) 

你得到:

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

对于经典的文件,你可以这样写:

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) 

您还可以将您的“记录”存储在列表中供将来使用:

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) 

你得到:

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

这是一个神奇的解决方案。谢谢! –

0
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) 

这会将值作为一个字典,然后可以用键调用搜索值。从这里,您可以创建复合词典(根据每行的键写入主词典),也可以随时搜索该值。

编辑,以配合洛朗的答案的风格。