Python将字符串转换为list,然后转换为som

2024-04-29 13:43:16 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我要做的是获取一个输入(见下文),并将格式转换为以下输出(见下文)。输出为字典列表。我一直在玩.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;'119','mac':'00:23:AE:90:FB:5B','name':'tellurium','room':无}

接近但没有雪茄,试图分开119


Tags: 代码nameipmaclinethisfilefa
3条回答

下面的列表从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()中的其他空白一起删除。未能从文本文件输入行中删除换行符可能会导致神秘的&;或恼人的行为。。。你知道吗

要删除前面带有;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

尝试:

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

Split Strings with Multiple Delimiters?

这将用空格替换分号,然后拆分。提供的链接将为在多个分隔符上拆分提供更通用的解决方案。你知道吗

相关问题 更多 >