简体   繁体   English

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

[英]Python converting string to list and then some

Basically what I am trying to do is take an input (see below) and convert the format to the following output (see below). 基本上,我想做的是输入(请参阅下文)并将格式转换为以下输出(请参阅下文)。 The output being a list of dictionaries. 输出是字典列表。 I have been playing with .split() and .strip() but I still having issues in separating the IP address with the room number. 我一直在玩.split()和.strip(),但是在将IP地址与房间号分开时仍然遇到问题。 (see my code below) (请参见下面的代码)

input: 输入:

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

output: 输出:

[{'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)

My code: 我的代码:

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

This is the output I'm getting: {'ip': '144.38.196.157";119', 'mac': '00:23:AE:90:FB:5B', 'name': 'tellurium', 'room': None} 这是我得到的输出:{'ip':'144.38.196.157“; 119','mac':'00:23:AE:90:FB:5B','name':'tellurium','房间”:无}

Close but no cigar, trying to separate the 119 关闭但没有雪茄,试图将119分开

The list comprehension below removes double quotes from line , then splits on semi-colons, then strips leading & trailing white space from each field in the line. 下面的列表理解从line中删除双引号,然后以分号分隔,然后从行中的每个字段中删除前导和尾随空白。 Then it extracts the fields to named variables using tuple assignment. 然后,它使用元组分配将字段提取到命名变量。

#! /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

output 输出

"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'}

I should mention that each line coming from your for line in file: will end in newline characters; 我应该提到for line in file:来自您for line in file:每一行for line in file:将以换行符结尾; my code removes that along with other white space with the s.strip() in the list comprehension. 我的代码使用列表s.strip()将其与其他空格一起删除。 Failure to remove newlines from text file input lines can lead to mysterious &/or annoying behaviour... 无法从文本文件输入行中删除换行符可能导致神秘和/或令人讨厌的行为...

Try: 尝试:

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

Split Strings with Multiple Delimiters? 用多个定界符分割字符串?

This replaces semicolon with space, then splits. 这将用空格替换分号,然后分割。 The link provided will give a more general solution to splitting on multiple delimiters. 提供的链接将为拆分多个分隔符提供更通用的解决方案。

Extracting using 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

Extracting using regex: 使用正则表达式提取:

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

Output: 输出:

[{'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'}]

To remove the 119 , which is preceded by a ; 删除119 ,后面加一个; , just split by the semi-colon: ,只是用分号split

line.split(';')

Return a list of the words in the string, using sep as the delimiter string. 使用sep作为分隔符字符串,返回字符串中单词的列表。

In your code: 在您的代码中:

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

After storing the valued in a variable 将值存储在变量中之后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM