开发者

Help with Python strings

I have a program which reads commands from a text file

for example, the command syntax will be as follows and is a string

'index command param1 param2 param3'

The number of parameters is variable from 0 up to 3 index is an integer command is a string all the params are integers

I would like to split them so that I have a list as follows

[i开发者_运维问答ndex,'command',params[]]

What is the best way to do this?

Thanks


Not sure if it's the best way, but here's one way:

lines = open('file.txt')
for line in lines:
   as_list = line.split()
   result = [as_list[0], as_list[1], as_list[2:]]
   print result

Result will contain

['index', 'command', ['param1', 'param2', 'param3']]


def add_command(index, command, *params):
    index = int(index)
    #do what you need to with index, command and params here

with open('commands.txt') as f:
    for line in f:
        add_command(*line.split())


i typically write:

lines = open('a.txt').readlines()
for line in lines:
    para = lines.split()
    index = int(para[0])
    command = para[1]
    para1 = float(para[2])
    ...


  1. Open the file
  2. Read each line and parse the line via line.split( )


>>> for line in open("file"):
...     line=line.rstrip().split(" ",2)
...     line[0]=int(line[0])
...     line[2]=line[2].split()
...     print line
...
[1, 'command', ['param1', 'param2', 'param3']]


If you use Python 3+, then following should be enough as indicated in PEP 3132: Extended Iterable Unpacking:

(index,command,*parameters) = line.split()

Otherwise, I like solution from James best:

def add_command(index, command, *params):
    ...


The Answer provided by cb160 is correct and smart way, But, I did it in this way. In cb160's code, Only thing is index should be in Integer format, as you have mentioned.

In my below code, I added exceptions for empty lines in input file if there are any.

#Example Input File: (file content)
"""
1 command1 parm1a parm1b parm1c
2 command2 parm2a parm2b parm2c

3 command3 parm3a parm3b parm3c

"""

li = []

for line in open('list_of_commands.txt'):
  try:
    lis = line.split()
    li.append([int(lis[0]),lis[1], lis[2:]])
  except IndexError:
    pass    # do nothing if empty lines are found

print li

Output

[1, 'command1', ['parm1a', 'parm1b', 'parm1c']]
[2, 'command2', ['parm2a', 'parm2b', 'parm2c']]
[3, 'command3', ['parm3a', 'parm3b', 'parm3c']]

let me know if I missed anything.

Thanks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜