简体   繁体   中英

Python : splitting and splitting

I need some help; I'm trying to program a sort of command prompt with python

I need to split a text file into lines then split them into strings

example :

splitting

command1 var1 var2;
command2 (blah, bleh);
command3 blah (b bleh);
command4 var1(blah b(bleh * var2));

into :

line1=['command1','var1','var2']

line2=['command2']
line2_sub1=['blah','bleh']

line3=['blah']
line3_sub1=['b','bleh']

line4=['command4']
line4_sub1=['blah','b']
line4_sub2=['bleh','var2']
line4_sub2_operand=['*']

Would that be possible at all? If so could some one explain how or give me a piece of code that would do it?

Thanks a lot,

It's been pointed out, that there appears to be no reasoning to your language. All I can do is point you to pyparsing , which is what I would use if I were solving a problem similar to this, here is a pyparsing example for the python language .

Like everyone else is saying, your language is confusingly designed and you probably need to simplify it. But I'm going to give you what you're looking for and let you figure that out the hard way.

The standard python file object (returned by open()) is an iterator of lines, and the split() method of the python string class splits a string into a list of substrings. So you'll probably want to start with something like:

for line in command_file
    words = line.split(' ')

http://docs.python.org/3/library/string.html

you could use this code to read the file line by line and split it by spaces between words.

a= True
f = open(filename)
while a:
    nextline=f.readline()
    wordlist= nextline.split("")
    print(wordlist)
    if nextline=="\n":
        a= False

What you're talking about is writing a simple programming language. It's not extraordinarily difficult if you know what you're doing, but it is the sort of thing most people take a full semester class to learn. The fact that you've got multiple different types of lexical units with what looks to be a non-trivial, recursive syntax means that you'll need a scanner and a parser. If you really want to teach yourself to do this, this might not be a bad place to start.

If you simplify your grammar such that each command only has a fixed number of arguments, you can probably get away with using regular expressions to represent the syntax of your individual commands.

Give it a shot. Just don't expect it to all work itself out overnight.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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