0

我想拆分键和值并显示下面提到的格式的字典结果。我正在读取一个文件并将数据拆分为列表,然后再转到字典。

请帮助我得到结果。

输入文件- commands.txt

login url=http://demo.url.net username=test@url.net password=mytester

create-folder foldername=demo

select-folder foldername=test123

logout

预期结果格式

print result_dict


        "0": {
            "login": [
                {
                    "url": "http://demo.url.net",
                    "username": "test@url.net",
                    "password": "mytester"
                }
            ]
        },
        "1": {
            "create-folder": {
                "foldername": "demo"
            }
        },
        "2": {
            "select-folder": {
                "foldername": "test-folder"
            }
        },
        "3": {
            "logout": {}
        }

代码

    file=os.path.abspath('catalog/commands.txt')
    list_output=[f.rstrip().split() for f in open(file).readlines()]
    print list_output

    counter=0
    for data in list_output:
        csvdata[counter]=data[0:]
        counter=counter+1   
    print csvdata

for key,val in csvdata.iteritems():
    for item in val:
        if '=' in item:
            key,value=item.split("=")
            result[key]=value

print result
4

3 回答 3

2

作为一个函数:

from collections import defaultdict
from itertools import count

def read_file(file_path):
    result = defaultdict(dict)
    item = count()
    with open(file_path) as f:
        for line in f:
            if not line:
                continue
            parts = line.split()
            result[next(item)][parts[0]] = dict(p.split('=') for p in parts[1:])
    return dict(result)

更好的例子和解释:

s = """
login url=http://demo.url.net username=test@url.net password=mytester

create-folder foldername=demo

select-folder foldername=test123

logout
"""

from collections import defaultdict
from itertools import count

result_dict = defaultdict(dict)
item = count()

# pretend you opened the file and are reading it line by line
for line in s.splitlines():
    if not line:
        continue # skip empty lines
    parts = line.split()
    result_dict[next(item)][parts[0]] = dict(p.split('=') for p in parts[1:])

漂亮的印刷品:

>>> pprint(dict(result_dict))
{0: {'login': {'password': 'mytester',
               'url': 'http://demo.url.net',
               'username': 'test@url.net'}},
 1: {'create-folder': {'foldername': 'demo'}},
 2: {'select-folder': {'foldername': 'test123'}},
 3: {'logout': {}}}
于 2013-10-30T13:46:59.947 回答
1
lines = ["login url=http://demo.url.net username=test@url.net password=mytester",
         "create-folder foldername=demo",
         "select-folder foldername=test123",
         "logout"]

result = {}
for no, line in enumerate(lines):
    values = line.split()
    pairs = [v.split('=') for v in values[1:]]
    result[str(no)] = {values[0]: [dict(pairs)] if len(pairs) > 1 else dict(pairs)}

import pprint
pprint.pprint(result)

输出:

{'0': {'login': [{'password': 'mytester',
                  'url': 'http://demo.url.net',
                  'username': 'test@url.net'}]},
 '1': {'create-folder': {'foldername': 'demo'}},
 '2': {'select-folder': {'foldername': 'test123'}},
 '3': {'logout': {}}}

但是你确定你需要login值内的额外列表吗?如果没有,只需更改[dict(pairs)] if len(pairs) > 1 else dict(pairs)dict(pairs).

于 2013-10-30T13:46:34.740 回答
0
r = dict()
f = open('commands.txt')

for i, line in enumerate(f.readlines()):
  r[str(i)] = dict()
  actions = line.split()
  list_actions = {}
  for action in actions[1:]:
    if "=" in action:
      k, v = action.split('=')
      list_actions[k] = v
  if len(actions[1:]) > 1:
    r[str(i)][actions[0]] = [list_actions]
  else:
    r[str(i)][actions[0]] = list_actions


print r

应该是工作

于 2013-10-30T13:53:53.797 回答