Python将字符串转换为列表,然后是一些

时间:2015-01-24 05:41:29

标签: python string dictionary string-formatting

基本上我要做的是接受输入(见下文)并将格式转换为以下输出(见下文)。输出是字典列表。我一直在玩.split()和.strip(),但我仍然在将IP地址与房间号分开时遇到问题。 (见下面的代码)

输入:

"bromine ";" 00:23:AE:90:FA:C6 ";" 144.38.198.130";151 #(this is just one line in the file, there are several lines with this exact format)

输出:

[{'ip': '144.38.198.130', 'mac': '00:23:AE:90:FA:C6', 'name': 'bromine', 'room': '151'}] #(again this would be just one of the lines)

我的代码:

import sys

my_list = []
file = sys.stdin
for line in file:
   # d = {}
    line = line.strip('"')
    line = line.split()

    name = line[0]
    macAddress = line[2]
    ipAddress = line[4]
    #roomNum = [?]

    d={'ip': ipAddress, 'mac': macAddress, 'name': name, 'room': None}
    my_list.append(d)
    #print line

print d

这是我得到的输出: {' ip':' 144.38.196.157&#34 ;; 119',' mac':' 00:23:AE:90:FB: 5B',' name':' tellurium',' room':None}

关闭但没有雪茄,试图分开119

5 个答案:

答案 0 :(得分:2)

下面的列表理解从line中删除双引号,然后在分号上分割,然后剥离前导&从行中的每个字段尾随空格。然后使用元组赋值将字段提取到命名变量。

#! /usr/bin/env python

line = '"bromine ";" 00:23:AE:90:FA:C6 ";" 144.38.198.130";151'
print line

line = [s.strip() for s in line.replace('"', '').split(';')]
print line

name, macAddress, ipAddress, roomNum = line
d = {'ip': ipAddress, 'mac': macAddress, 'name': name, 'room': roomNum}

print d

<强>输出

"bromine ";" 00:23:AE:90:FA:C6 ";" 144.38.198.130";151
['bromine', '00:23:AE:90:FA:C6', '144.38.198.130', '151']
{'ip': '144.38.198.130', 'mac': '00:23:AE:90:FA:C6', 'name': 'bromine', 'room': '151'}

我应该提到来自for line in file:的每一行都会以换行符结尾;我的代码将其与列表推导中s.strip()的其他空格一起删除。无法从文本文件输入行中删除换行符可能会导致神秘和/或恼人的行为......

答案 1 :(得分:1)

尝试:

line.replace(';',' ').split()

Split Strings with Multiple Delimiters?

用空格替换分号,然后拆分。提供的链接将为分割多个分隔符提供更通用的解决方案。

答案 2 :(得分:0)

使用replace / strip提取:

import sys

my_list = []
f = sys.stdin

for line in f:
    line = line.split('";')
    result = dict(
                  zip(["name", "mac", "ip", "room"],
                  [field.replace('"', "").strip() for field in line]))
    my_list.append(result)

print my_list

使用正则表达式提取:

import sys
import re

my_list = []
f = sys.stdin

pattern = r'"(\w*)\W*([\w:]*)\W*([\w\.]*)";(\w*)'
for line in f:
    result = dict(
        zip(["name", "mac", "ip", "room"],
            re.match(pattern, line).groups()))
    my_list.append(result)

print my_list

输出:

[{'ip': '144.38.198.130', 'mac': '00:23:AE:90:FA:C6', 'name': 'bromine', 'room': '151'},
{'ip': '144.38.196.157', 'mac': '00:23:AE:90:FB:5B', 'name': 'tellurium', 'room': '119'}]

答案 3 :(得分:0)

要删除119,前面有;,只需用分号删除split

line.split(';')
  

Return a list of the words in the string, using sep as the delimiter string.

在您的代码中:

import sys

my_list = []
file = sys.stdin
for line in file:
   # d = {}
    line = line.strip('"')
    line = line.split()[0]
    name = line.split(';')[0]

    macAddress = line[2]
    ipAddress = line[4]
    #roomNum = [?]

    d={'ip': ipAddress, 'mac': macAddress, 'name': name, 'room': None}
    my_list.append(d)
    #print line

print d

答案 4 :(得分:0)

将值存储在变量

import re
input = '"a";"b";"c";"d"'
keys = ['x','y','z','w']
inputlist = input.split(';')
for x in range(0, len(inputlist)):
    inputlist[x] = re.sub(r'"','',inputlist [x])
output = dict(zip(keys,inputlist))