Question

I know this is a basic question, but I'm having difficult with parsing some text.

So how the system will work, let's take the following example:

> set title "Hello world" 

I should therefore get:

["set title", "Hello world"] 

The problem is therefore, I need to split the string so when I enter, for example:

> plot("data.txt"); 

Should give me:

["plot", "data.txt"] 

I have tried the following:

While True:
       command = raw_input(">");
       parse = command.split("' '");

       if(parse[0] == "set title"):
               title = parse[1];

But this does not work and will not even recognise that I am entering "set title"

Any ideas?

Was it helpful?

Solution

You don't need split. You need re:

import re
def parse(command):
    regex = r'(.*) "(.*)"'
    items = list(re.match(regex, command).groups())
    return items

if __name__ == '__main__':
    command = 'set title "Hello world"'
    print parse(command)

returns

['set title', 'Hello world']

OTHER TIPS

split("' '")

Will split on the literal sequence of three characters single quote, space, single quote, which don't appear in your command strings.

I think you will need to approach this more like:

command, content = command.split(" ", 1)
if command == "plot":
    plot(command[1:-1])
elif command == "set":
    item, content = content.split(" ", 1)
        if item == "title":
            title = content[1:-1]
...

Note the use of a second argument to tell split how many times to do so; 'set title "foo"'.split(" ", 1) == ['set', 'title "foo"']. Precisely how you implement will depend on the range of things you want to be able to parse.

To split the string by blanks you need to use

parse = command.split(' ')

For the input "set title" you will get a parse array looking like this

['set', 'title']

where parse[0] == 'set' and parse[1] == 'title'

If you want to test whether your string starts with "set title", either check the command string itself or check the first two indexes of parse.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top