newbe's re question

E

Eric_Dexter

All I am after realy is to change this

reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces.. this is a corrected version from

http://python-forum.org/py/viewtopic.php?t=1703

thanks in advance the hole routine is down below..






Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

    "takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
    f = open (input_File_Name , 'r')                #opens file passed
in to read
    f2 = open (output_File_Name, 'w')               #opens file passed
in to write
    instr_yes = 'false'                             #set flag to false

    for line in f:                                  #for through all
the lines
      if "instr" in line:                           #look for instr in
the file
           if instr_yes == 'true':                    #check to see if
this ends the instr block
               break                                #exit the block

           reline = re.line.split('instr', '/d$')     #error probily
split instr and /d (decimal number into parts) $ for end of line
           number = int(reline[1])                  #convert to a
number maybe not important
                if number == instr_number:            #check to see if
it is the instr passed to function
                instr_yes = "true":                 #change flag to
true because this is the instr we want
      if instr_yes = "true":                        #start of code to
copy to another file
           f2.write(f.line)                         #write line to
output file

    f.close                                         #close input file
    f2.close
 
G

George Sakkis

All I am after realy is to change this

reline = re.line.split('instr', '/d$')

If you think this is the only problem in your code, think again; almost
every other line has an error or an unpythonic idiom. Have you read any
tutorial or sample code before typing this python-like pseudocode ?

George
 
E

Eric_Dexter

George said:
If you think this is the only problem in your code, think again; almost
every other line has an error or an unpythonic idiom. Have you read any
tutorial or sample code before typing this python-like pseudocode ?

George

better to offend a python than a rattlesnake (you have to see the cwa
rattlesnake shirts shirts compared to the python shirts) :)

As long as it will run but I feel like I am just converting it to
something that feels like c somewhat but I am learning the commands
(hopefully).. hard to get a good chapters with questions at the end
without cash... I am happy even if the code isn't pythonic if it runs
with this.

import csoundroutines

extractCsdInstrument("bay-at-night.csd", "test.orc", 1)

http://www.dexrow.com
 
M

MonkeeSage

Hi Eric,

Don't let people offput you from learning python. It's a great
language, and is fun to use. But really, George does have a point -- if
you want to learn python, then the best way is to swim with the tide
rather than against it. But still, don't worry too much about being
pythonic and whatnot (many people would disagree with me here), just
write the code that _you_ (and your team) feel the most comfortable
with, and helps you be the most productive. But again, many of the
conventional pythonic ways to do things are such because people have
tested various ways and found those to be the best. So don't just blow
off convention, either. Find a happy medium between your coding style
and the conventions, and then you'll really become as productive as you
can be. That's my opinion. And only my opinion. But if it helps you
too, that's good. :)

Ps. Do have a look at the tutorials and other guides available, they
should help you out alot (e.g., the regexp tutorial [1]).

[1] http://www.amk.ca/python/howto/regex/

Regards,
Jordan
 
D

Dennis Lee Bieber

Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')                #opens file passed
in to read
f2 = open (output_File_Name, 'w')               #opens file passed
in to write
instr_yes = 'false'                             #set flag to false

for line in f:                                  #for through all
the lines
if "instr" in line:                           #look for instr in
the file
if instr_yes == 'true':                    #check to see if
this ends the instr block
break                                #exit the block

reline = re.line.split('instr', '/d$')     #error probily
split instr and /d (decimal number into parts) $ for end of line
number = int(reline[1])                  #convert to a
number maybe not important
if number == instr_number:            #check to see if
it is the instr passed to function
instr_yes = "true":                 #change flag to
true because this is the instr we want
if instr_yes = "true":                        #start of code to
copy to another file
f2.write(f.line)                         #write line to
output file

f.close                                         #close input file
f2.close

Step one... Read a book on Python language syntax. Python has had
booleans for some time yet you are doing explicit comparisons against
STRINGS. You have ":" at the end of some lines that don't need them (and
are in error because of them). You seem to think you can manipulate a
variable "line" using other packages by just putting it with a . -- And
you fail to call the file close methods.

Now, looking at
http://www.csounds.com/manual/html/CommandUnifileFormat.html seems to
imply that a CSD file is a form of XML.

So...

-=-=-=-=-=-=-=- test.py
from xml.dom.minidom import parse

FN_IN = "test.csd"
FN_OUT = "test.txt"

def extractInstrument(section, instrument_number):
out = []
for node in section:
found = False
for ln in node.data.split("\n"):
ln = ln.strip()
if ln.startswith("endin"):
found = False
if ln.startswith("instr"):
fields = ln.split()
number = int(fields[1])
ln = " ".join(fields[2:])
found = number == instrument_number
if found:
out.append(ln)
return "\n".join(out)

fout = open(FN_OUT, "w")

dom = parse(FN_IN)
nodeList = dom.getElementsByTagName("CsInstruments")

for node in nodeList:
fout.writelines(extractInstrument(node.childNodes, 1))

fout.close()
-=-=-=-=-=-=-=-=-=- test.csd (straight from the web site)
<CsoundSynthesizer>;
; test.csd - a Csound structured data file

<CsOptions>
-W -d -o tone.wav
</CsOptions>

<CsVersion> ;optional section
Before 4.10 ;these two statements check for
After 4.08 ; Csound version 4.09
</CsVersion>

<CsInstruments>
; originally tone.orc
sr = 44100
kr = 4410
ksmps = 10
nchnls = 1
instr 1
a1 oscil p4, p5, 1 ; simple oscillator
out a1
endin
</CsInstruments>

<CsScore>
; originally tone.sco
f1 0 8192 10 1
i1 0 1 20000 1000 ;play one second of one kHz tone
e
</CsScore>

</CsoundSynthesizer>
-=-=-=-=-=-=-=-=-=- test.txt

a1 oscil p4, p5, 1 ; simple oscillator
out a1
-=-=-=-=-=-=-=-=-=-
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
E

Eric

All I am after realy is to change this

reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces.

Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):
"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')
f2 = open (output_File_Name, 'w')
instr_yes = 'false' # Python has built-in booleans
# Also, use sane naming: isInstr or hasInstr

for line in f:
if "instr" in line:
if instr_yes == 'true': # Use the bool -- `if hasInstr:`
break

reline = re.line.split('instr', '/d$')     # ???
number = int(reline[1])
if number == instr_number:      # Doesn't need to be 2 lines
instr_yes = "true":                 # the `:` is a syntax error
if instr_yes = "true":
f2.write(f.line) # odd way of doing it...

f.close()
f2.close()

Did you read the HOWTO on regular expressions yet? It's included with
the standard documentation, but here's a link:

http://www.amk.ca/python/howto/regex/

Now, onto the issues:
1) The escape character is \, not /. Use "\d" to match a number.

2) I'm not sure I understand what you're trying to extract with your
regex. As it is, the expression will return a list containing one item,
a string identical to the line being matched up to, but not including,
the first number. The rest of the line will be discarded. Try Kiki, a
tool for testing regular expressions, before burying the expression in
your code.

3) Python has built-in booleans: True and False, no quotes. Use them so
that you don't get flamed on forums.

4) I don't claim to be a Python guru, but here's a massaged version of
the function you gave:

Code:
def extractCsdInstrument (inputPath, outputPath, instrId):
    """ Takes a .csd file, grabs info for instrument ID and writes to
file. """
    src = open(inputPath, 'r')
    dst = open(outputPath, 'w')
    for line in src:
	if "instr" in line:
	    info_comment = line.split(";", 1) # [info, comment]
            # Extract integers
            instrInfo = re.split(r"[^0-9]*", info_comment[0])
            # Check the second number in the line
            if instrInfo[1] == str(instrId):
		dst.write(instrInfo.append(info_comment[1]))
    src.close()
    dst.close()

I didn't check if this actually works, since I don't know what a .csd
file looks like. There are of course other, better ways to do it, but
hopefully this leads you in the right direction.

5) Please, read the documentation that came with your Python
installation. Reading up on string methods etc. ahead of time will save
you much more time than trying to slug through it. Also consider using
a text editor with syntax highlighting; that will help catch most
obvious syntax errors during coding.
 
D

Dennis Lee Bieber

Now, looking at
http://www.csounds.com/manual/html/CommandUnifileFormat.html seems to
imply that a CSD file is a form of XML.
I should add: This is only the second time I've written code to do
/anything/ with XML (and the first time was using an older version of
Python -- and I had a heck of a time with the Unicode results)
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
F

Frederic Rentsch

All I am after realy is to change this

reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces.. this is a corrected version from

http://python-forum.org/py/viewtopic.php?t=1703

thanks in advance the hole routine is down below..






Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')                #opens file passed
in to read
f2 = open (output_File_Name, 'w')               #opens file passed
in to write
instr_yes = 'false'                             #set flag to false

for line in f:                                  #for through all
the lines
if "instr" in line:                           #look for instr in
the file
if instr_yes == 'true':                    #check to see if
this ends the instr block
break                                #exit the block

reline = re.line.split('instr', '/d$')     #error probily
split instr and /d (decimal number into parts) $ for end of line
number = int(reline[1])                  #convert to a
number maybe not important
if number == instr_number:            #check to see if
it is the instr passed to function
instr_yes = "true":                 #change flag to
true because this is the instr we want
if instr_yes = "true":                        #start of code to
copy to another file
f2.write(f.line)                         #write line to
output file

f.close                                         #close input file
f2.close
Eric,
From your problem description and your code it is unclear what
exactly it is you want. The task appears to be rather simple, though,
and if you don't get much useful help I'd say it is because you don't
explain it very well.
I believe we've been through this before and your input data is
like this

data = '''
<CsoundSynthesizer>;
; test.csd - a Csound structured data file

<CsOptions>
-W -d -o tone.wav
</CsOptions>

<CsVersion> ;optional section
Before 4.10 ;these two statements check for
After 4.08 ; Csound version 4.09
</CsVersion>

<CsInstruments>
; originally tone.orc
sr = 44100
kr = 4410
ksmps = 10
nchnls = 1
instr 1
a1 oscil p4, p5, 1 ; simple oscillator
out a1
endin
</CsInstruments>

<CsScore>
; originally tone.sco
f1 0 8192 10 1
i1 0 1 20000 1000 ;play one second of one kHz tone
e
</CsScore>

</CsoundSynthesizer>

Question 1: Is this your input?
if yes:
Question 1.1: What do you want to extract from it? In what format?
if no:
Question 1.1: What is your input?
Question 1.2: What do you want to extract from it? In what format?
Question 2: Do you need to generate output file names from the data?
(One file per instrument?)
if yes:
Question 2.1: What do you want to make your file name from?
(Instrument number?)


Regards

Frederic
 
E

Eric_Dexter

Frederic said:
All I am after realy is to change this

reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces.. this is a corrected version from

http://python-forum.org/py/viewtopic.php?t=1703

thanks in advance the hole routine is down below..






Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')                #opens file passed
in to read
f2 = open (output_File_Name, 'w')               #opens file passed
in to write
instr_yes = 'false'                             #set flag to false

for line in f:                                  #for through all
the lines
if "instr" in line:                           #look for instr in
the file
if instr_yes == 'true':                    #check to see if
this ends the instr block
break                                #exit the block

reline = re.line.split('instr', '/d$')     #error probily
split instr and /d (decimal number into parts) $ for end of line
number = int(reline[1])                  #convert to a
number maybe not important
if number == instr_number:            #check to see if
it is the instr passed to function
instr_yes = "true":                 #change flag to
true because this is the instr we want
if instr_yes = "true":                        #start of code to
copy to another file
f2.write(f.line)                         #write line to
output file

f.close                                         #close input file
f2.close
Eric,
From your problem description and your code it is unclear what
exactly it is you want. The task appears to be rather simple, though,
and if you don't get much useful help I'd say it is because you don't
explain it very well.
I believe we've been through this before and your input data is
like this

data = '''
<CsoundSynthesizer>;
; test.csd - a Csound structured data file

<CsOptions>
-W -d -o tone.wav
</CsOptions>

<CsVersion> ;optional section
Before 4.10 ;these two statements check for
After 4.08 ; Csound version 4.09
</CsVersion>

<CsInstruments>
; originally tone.orc
sr = 44100
kr = 4410
ksmps = 10
nchnls = 1
instr 1
a1 oscil p4, p5, 1 ; simple oscillator
out a1
endin
</CsInstruments>

<CsScore>
; originally tone.sco
f1 0 8192 10 1
i1 0 1 20000 1000 ;play one second of one kHz tone
e
</CsScore>

</CsoundSynthesizer>

Question 1: Is this your input?
if yes:
Question 1.1: What do you want to extract from it? In what format?
if no:
Question 1.1: What is your input?
Question 1.2: What do you want to extract from it? In what format?
Question 2: Do you need to generate output file names from the data?
(One file per instrument?)
if yes:
Question 2.1: What do you want to make your file name from?
(Instrument number?)


Regards

Frederic

I want to pass the file name to the subroutine and return a comment
string if it is there maybe it should be simplier. I probily should
have the option of grabbing the comment in other related routines. I
am pretty ambitious with the main program. I did notice some code in
tcl that would be usefull to the app If I compile it.. I am probily
not ready for that though..

http://www.dexrow.com
 
F

Frederic Rentsch

Frederic said:
All I am after realy is to change this

reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces.. this is a corrected version from

http://python-forum.org/py/viewtopic.php?t=1703

thanks in advance the hole routine is down below..






Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')                #opens file passed
in to read
f2 = open (output_File_Name, 'w')               #opens file passed
in to write
instr_yes = 'false'                             #set flag to false

for line in f:                                  #for through all
the lines
if "instr" in line:                           #look for instr in
the file
if instr_yes == 'true':                    #check to see if
this ends the instr block
break                                #exit the block

reline = re.line.split('instr', '/d$')     #error probily
split instr and /d (decimal number into parts) $ for end of line
number = int(reline[1])                  #convert to a
number maybe not important
if number == instr_number:            #check to see if
it is the instr passed to function
instr_yes = "true":                 #change flag to
true because this is the instr we want
if instr_yes = "true":                        #start of code to
copy to another file
f2.write(f.line)                         #write line to
output file

f.close                                         #close input file
f2.close
Eric,
From your problem description and your code it is unclear what
exactly it is you want. The task appears to be rather simple, though,
and if you don't get much useful help I'd say it is because you don't
explain it very well.
I believe we've been through this before and your input data is
like this

data = '''
<CsoundSynthesizer>;
; test.csd - a Csound structured data file

<CsOptions>
-W -d -o tone.wav
</CsOptions>

<CsVersion> ;optional section
Before 4.10 ;these two statements check for
After 4.08 ; Csound version 4.09
</CsVersion>

<CsInstruments>
; originally tone.orc
sr = 44100
kr = 4410
ksmps = 10
nchnls = 1
instr 1
a1 oscil p4, p5, 1 ; simple oscillator
out a1
endin
</CsInstruments>

<CsScore>
; originally tone.sco
f1 0 8192 10 1
i1 0 1 20000 1000 ;play one second of one kHz tone
e
</CsScore>

</CsoundSynthesizer>

Question 1: Is this your input?
if yes:
Question 1.1: What do you want to extract from it? In what format?
if no:
Question 1.1: What is your input?
Question 1.2: What do you want to extract from it? In what format?
Question 2: Do you need to generate output file names from the data?
(One file per instrument?)
if yes:
Question 2.1: What do you want to make your file name from?
(Instrument number?)


Regards

Frederic

I want to pass the file name to the subroutine and return a comment
string if it is there maybe it should be simplier. I probily should
have the option of grabbing the comment in other related routines. I
am pretty ambitious with the main program. I did notice some code in
tcl that would be usefull to the app If I compile it.. I am probily
not ready for that though..

http://www.dexrow.com

Eric,
I'm beginning to enjoy this. I'm sure we'll sort this out in no
time if we proceed methodically. Imagine you are a teacher and I am your
student. This is a quiz. I have to take it and you need to explain to me
the problem you want me to solve. If you don't explain it clearly, I
will not know what I have to do and cannot do the quiz. If you answer my
questions above, your description of the problem will be clear and I can
take the quiz. Okay?

Frederic
 
E

Eric_Dexter

Frederic said:
Frederic said:
(e-mail address removed) wrote:

All I am after realy is to change this

reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces.. this is a corrected version from

http://python-forum.org/py/viewtopic.php?t=1703

thanks in advance the hole routine is down below..






Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')                #opens file passed
in to read
f2 = open (output_File_Name, 'w')               #opens file passed
in to write
instr_yes = 'false'                             #set flag to false

for line in f:                                  #for through all
the lines
if "instr" in line:                           #look for instr in
the file
if instr_yes == 'true':                    #check to see if
this ends the instr block
break                                #exit the block

reline = re.line.split('instr', '/d$')     #error probily
split instr and /d (decimal number into parts) $ for end of line
number = int(reline[1])                  #convert to a
number maybe not important
if number == instr_number:            #check to see if
it is the instr passed to function
instr_yes = "true":                 #change flag to
true because this is the instr we want
if instr_yes = "true":                        #start of code to
copy to another file
f2.write(f.line)                         #write line to
output file

f.close                                         #close input file
f2.close



Eric,
From your problem description and your code it is unclear what
exactly it is you want. The task appears to be rather simple, though,
and if you don't get much useful help I'd say it is because you don't
explain it very well.
I believe we've been through this before and your input data is
like this

data = '''
<CsoundSynthesizer>;
; test.csd - a Csound structured data file

<CsOptions>
-W -d -o tone.wav
</CsOptions>

<CsVersion> ;optional section
Before 4.10 ;these two statements check for
After 4.08 ; Csound version 4.09
</CsVersion>

<CsInstruments>
; originally tone.orc
sr = 44100
kr = 4410
ksmps = 10
nchnls = 1
instr 1
a1 oscil p4, p5, 1 ; simple oscillator
out a1
endin
</CsInstruments>

<CsScore>
; originally tone.sco
f1 0 8192 10 1
i1 0 1 20000 1000 ;play one second of one kHz tone
e
</CsScore>

</CsoundSynthesizer>

Question 1: Is this your input?
if yes:
Question 1.1: What do you want to extract from it? In what format?
if no:
Question 1.1: What is your input?
Question 1.2: What do you want to extract from it? In what format?
Question 2: Do you need to generate output file names from the data?
(One file per instrument?)
if yes:
Question 2.1: What do you want to make your file name from?
(Instrument number?)


Regards

Frederic

I want to pass the file name to the subroutine and return a comment
string if it is there maybe it should be simplier. I probily should
have the option of grabbing the comment in other related routines. I
am pretty ambitious with the main program. I did notice some code in
tcl that would be usefull to the app If I compile it.. I am probily
not ready for that though..

http://www.dexrow.com

Eric,
I'm beginning to enjoy this. I'm sure we'll sort this out in no
time if we proceed methodically. Imagine you are a teacher and I am your
student. This is a quiz. I have to take it and you need to explain to me
the problem you want me to solve. If you don't explain it clearly, I
will not know what I have to do and cannot do the quiz. If you answer my
questions above, your description of the problem will be clear and I can
take the quiz. Okay?

Frederic


instr 1
a1 oscil p4, p5, 1 ; simple oscillator ; comment is
sometimes here
out a1
endin


I need to know the file I wan't to grab this from I need to grab this
out of the larger file and put it into it's own file, I need to know
what instr the user wants. I need to know what file to put it into and
it would be usefull to have the comment line returned (if any).

I did just get python essential reference 3rd edition.. If there is a
better reference on just the subject I am after I would be glad to grab
it when I get cash again.
 
D

Dennis Lee Bieber

Frederic Rentsch wrote:



instr 1
a1 oscil p4, p5, 1 ; simple oscillator ; comment is
sometimes here
out a1
endin


I need to know the file I wan't to grab this from I need to grab this
out of the larger file and put it into it's own file, I need to know
what instr the user wants. I need to know what file to put it into and
it would be usefull to have the comment line returned (if any).
You're not too clear on what are inputs, outputs, and processing...

"I need to know the file i wan't (sic) to grab this from" is vague
enough to cover everything from "ask at run time" to "read data from
stdin" (I/O redirection).

"I need to grab this out the larger file" -- you still haven't
confirmed that the file format we've grabbed from some web site
describing "csd" files really IS the format you are processing.

"I need to know what instr the user wants" could, again mean
anything from a command line argument, a prompt to the user, or even
"parse the file first and present a list of 'instr' entries found".

Same for "file to put it into": prompt the user, generate a name
internally based upon known inputs, write to stdout (using I/O
redirection to get to a file). You also don't describe the format the
output is supposed to contain -- just a straight copy of lines between
"instr" and "endin", or is some other XML blocking supposed to be used.

And, if the web site was the format of the input, what does "the
comment line" mean, since comments can be put on every line! The first
comment found, the last found, collect them up into one list, join them
into one string?

I'd posted a /working/ example a day or so ago, using the sample
file found on the web site. Have you looked at it?
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
F

Frederic Rentsch

Frederic said:
Frederic Rentsch wrote:


(e-mail address removed) wrote:


All I am after realy is to change this

reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces.. this is a corrected version from

http://python-forum.org/py/viewtopic.php?t=1703

thanks in advance the hole routine is down below..






Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')                #opens file passed
in to read
f2 = open (output_File_Name, 'w')               #opens file passed
in to write
instr_yes = 'false'                             #set flag to false

for line in f:                                  #for through all
the lines
if "instr" in line:                           #look for instr in
the file
if instr_yes == 'true':                    #check to see if
this ends the instr block
break                                #exit the block

reline = re.line.split('instr', '/d$')     #error probily
split instr and /d (decimal number into parts) $ for end of line
number = int(reline[1])                  #convert to a
number maybe not important
if number == instr_number:            #check to see if
it is the instr passed to function
instr_yes = "true":                 #change flag to
true because this is the instr we want
if instr_yes = "true":                        #start of code to
copy to another file
f2.write(f.line)                         #write line to
output file

f.close                                         #close input file
f2.close




Eric,
From your problem description and your code it is unclear what
exactly it is you want. The task appears to be rather simple, though,
and if you don't get much useful help I'd say it is because you don't
explain it very well.
I believe we've been through this before and your input data is
like this

data = '''
<CsoundSynthesizer>;
; test.csd - a Csound structured data file

<CsOptions>
-W -d -o tone.wav
</CsOptions>

<CsVersion> ;optional section
Before 4.10 ;these two statements check for
After 4.08 ; Csound version 4.09
</CsVersion>

<CsInstruments>
; originally tone.orc
sr = 44100
kr = 4410
ksmps = 10
nchnls = 1
instr 1
a1 oscil p4, p5, 1 ; simple oscillator
out a1
endin
</CsInstruments>

<CsScore>
; originally tone.sco
f1 0 8192 10 1
i1 0 1 20000 1000 ;play one second of one kHz tone
e
</CsScore>

</CsoundSynthesizer>

Question 1: Is this your input?
if yes:
Question 1.1: What do you want to extract from it? In what format?
if no:
Question 1.1: What is your input?
Question 1.2: What do you want to extract from it? In what format?
Question 2: Do you need to generate output file names from the data?
(One file per instrument?)
if yes:
Question 2.1: What do you want to make your file name from?
(Instrument number?)


Regards

Frederic


I want to pass the file name to the subroutine and return a comment
string if it is there maybe it should be simplier. I probily should
have the option of grabbing the comment in other related routines. I
am pretty ambitious with the main program. I did notice some code in
tcl that would be usefull to the app If I compile it.. I am probily
not ready for that though..

http://www.dexrow.com
Eric,
I'm beginning to enjoy this. I'm sure we'll sort this out in no
time if we proceed methodically. Imagine you are a teacher and I am your
student. This is a quiz. I have to take it and you need to explain to me
the problem you want me to solve. If you don't explain it clearly, I
will not know what I have to do and cannot do the quiz. If you answer my
questions above, your description of the problem will be clear and I can
take the quiz. Okay?

Frederic


instr 1
a1 oscil p4, p5, 1 ; simple oscillator ; comment is
sometimes here
out a1
endin


I need to know the file I wan't to grab this from I need to grab this
out of the larger file and put it into it's own file, I need to know
what instr the user wants. I need to know what file to put it into and
it would be usefull to have the comment line returned (if any).

I did just get python essential reference 3rd edition.. If there is a
better reference on just the subject I am after I would be glad to grab
it when I get cash again.

Eric,

Tell us the story. Are you a student? A musician? What are you doing
with these files? Where do you get them from? What for?

Frederic
 
E

Eric_Dexter

These are csound files. Csound recently added python as a scripting
language and is allowing also allowing csound calls from outside of
csound. The nice thing about csound is that instead of worrying about
virus and large files it is an interpiter and all the files look
somewhat like html. 4,000 virus free instruments for $20 is available
at
http://www.csounds.com and the csound programming book is also
available. The downside is that csound is can be realy ugly looking
(that is what I am trying to change) and it lets you write ugly looking
song code that is almost unreadable at times (would look nice in a
grid)

http://www.msn.com
...


Frederic said:
Frederic said:
(e-mail address removed) wrote:

Frederic Rentsch wrote:


(e-mail address removed) wrote:


All I am after realy is to change this

reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces.. this is a corrected version from

http://python-forum.org/py/viewtopic.php?t=1703

thanks in advance the hole routine is down below..






Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')                #opens file passed
in to read
f2 = open (output_File_Name, 'w')               #opens file passed
in to write
instr_yes = 'false'                             #set flag to false

for line in f:                                  #for through all
the lines
if "instr" in line:                           #look for instr in
the file
if instr_yes == 'true':                    #check to see if
this ends the instr block
break                                #exit the block

reline = re.line.split('instr', '/d$')     #error probily
split instr and /d (decimal number into parts) $ for end of line
number = int(reline[1])                  #convert to a
number maybe not important
if number == instr_number:            #check to see if
it is the instr passed to function
instr_yes = "true":                 #change flag to
true because this is the instr we want
if instr_yes = "true":                        #start of code to
copy to another file
f2.write(f.line)                         #write line to
output file

f.close                                         #close input file
f2.close




Eric,
From your problem description and your code it is unclear what
exactly it is you want. The task appears to be rather simple, though,
and if you don't get much useful help I'd say it is because you don't
explain it very well.
I believe we've been through this before and your input data is
like this

data = '''
<CsoundSynthesizer>;
; test.csd - a Csound structured data file

<CsOptions>
-W -d -o tone.wav
</CsOptions>

<CsVersion> ;optional section
Before 4.10 ;these two statements check for
After 4.08 ; Csound version 4.09
</CsVersion>

<CsInstruments>
; originally tone.orc
sr = 44100
kr = 4410
ksmps = 10
nchnls = 1
instr 1
a1 oscil p4, p5, 1 ; simple oscillator
out a1
endin
</CsInstruments>

<CsScore>
; originally tone.sco
f1 0 8192 10 1
i1 0 1 20000 1000 ;play one second of one kHz tone
e
</CsScore>

</CsoundSynthesizer>

Question 1: Is this your input?
if yes:
Question 1.1: What do you want to extract from it? In what format?
if no:
Question 1.1: What is your input?
Question 1.2: What do you want to extract from it? In what format?
Question 2: Do you need to generate output file names from the data?
(One file per instrument?)
if yes:
Question 2.1: What do you want to make your file name from?
(Instrument number?)


Regards

Frederic


I want to pass the file name to the subroutine and return a comment
string if it is there maybe it should be simplier. I probily should
have the option of grabbing the comment in other related routines. I
am pretty ambitious with the main program. I did notice some code in
tcl that would be usefull to the app If I compile it.. I am probily
not ready for that though..

http://www.dexrow.com



Eric,
I'm beginning to enjoy this. I'm sure we'll sort this out in no
time if we proceed methodically. Imagine you are a teacher and I am your
student. This is a quiz. I have to take it and you need to explain to me
the problem you want me to solve. If you don't explain it clearly, I
will not know what I have to do and cannot do the quiz. If you answer my
questions above, your description of the problem will be clear and I can
take the quiz. Okay?

Frederic


instr 1
a1 oscil p4, p5, 1 ; simple oscillator ; comment is
sometimes here
out a1
endin


I need to know the file I wan't to grab this from I need to grab this
out of the larger file and put it into it's own file, I need to know
what instr the user wants. I need to know what file to put it into and
it would be usefull to have the comment line returned (if any).

I did just get python essential reference 3rd edition.. If there is a
better reference on just the subject I am after I would be glad to grab
it when I get cash again.

Eric,

Tell us the story. Are you a student? A musician? What are you doing
with these files? Where do you get them from? What for?

Frederic
 
F

Frederic Rentsch

These are csound files. Csound recently added python as a scripting
language and is allowing also allowing csound calls from outside of
csound. The nice thing about csound is that instead of worrying about
virus and large files it is an interpiter and all the files look
somewhat like html. 4,000 virus free instruments for $20 is available
at
http://www.csounds.com and the csound programming book is also
available. The downside is that csound is can be realy ugly looking
(that is what I am trying to change) and it lets you write ugly looking
song code that is almost unreadable at times (would look nice in a
grid)

http://www.msn.com
..


Frederic said:
Frederic Rentsch wrote:


(e-mail address removed) wrote:


Frederic Rentsch wrote:



(e-mail address removed) wrote:



All I am after realy is to change this

reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces.. this is a corrected version from

http://python-forum.org/py/viewtopic.php?t=1703

thanks in advance the hole routine is down below..






Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')                #opens file passed
in to read
f2 = open (output_File_Name, 'w')               #opens file passed
in to write
instr_yes = 'false'                             #set flag to false

for line in f:                                  #for through all
the lines
if "instr" in line:                           #look for instr in
the file
if instr_yes == 'true':                    #check to see if
this ends the instr block
break                                #exit the block

reline = re.line.split('instr', '/d$')     #error probily
split instr and /d (decimal number into parts) $ for end of line
number = int(reline[1])                  #convert to a
number maybe not important
if number == instr_number:            #check to see if
it is the instr passed to function
instr_yes = "true":                 #change flag to
true because this is the instr we want
if instr_yes = "true":                        #start of code to
copy to another file
f2.write(f.line)                         #write line to
output file

f.close                                         #close input file
f2.close





Eric,
From your problem description and your code it is unclear what
exactly it is you want. The task appears to be rather simple, though,
and if you don't get much useful help I'd say it is because you don't
explain it very well.
I believe we've been through this before and your input data is
like this

data = '''
<CsoundSynthesizer>;
; test.csd - a Csound structured data file

<CsOptions>
-W -d -o tone.wav
</CsOptions>

<CsVersion> ;optional section
Before 4.10 ;these two statements check for
After 4.08 ; Csound version 4.09
</CsVersion>

<CsInstruments>
; originally tone.orc
sr = 44100
kr = 4410
ksmps = 10
nchnls = 1
instr 1
a1 oscil p4, p5, 1 ; simple oscillator
out a1
endin
</CsInstruments>

<CsScore>
; originally tone.sco
f1 0 8192 10 1
i1 0 1 20000 1000 ;play one second of one kHz tone
e
</CsScore>

</CsoundSynthesizer>

Question 1: Is this your input?
if yes:
Question 1.1: What do you want to extract from it? In what format?
if no:
Question 1.1: What is your input?
Question 1.2: What do you want to extract from it? In what format?
Question 2: Do you need to generate output file names from the data?
(One file per instrument?)
if yes:
Question 2.1: What do you want to make your file name from?
(Instrument number?)


Regards

Frederic



I want to pass the file name to the subroutine and return a comment
string if it is there maybe it should be simplier. I probily should
have the option of grabbing the comment in other related routines. I
am pretty ambitious with the main program. I did notice some code in
tcl that would be usefull to the app If I compile it.. I am probily
not ready for that though..

http://www.dexrow.com




Eric,
I'm beginning to enjoy this. I'm sure we'll sort this out in no
time if we proceed methodically. Imagine you are a teacher and I am your
student. This is a quiz. I have to take it and you need to explain to me
the problem you want me to solve. If you don't explain it clearly, I
will not know what I have to do and cannot do the quiz. If you answer my
questions above, your description of the problem will be clear and I can
take the quiz. Okay?

Frederic


instr 1
a1 oscil p4, p5, 1 ; simple oscillator ; comment is
sometimes here
out a1
endin


I need to know the file I wan't to grab this from I need to grab this
out of the larger file and put it into it's own file, I need to know
what instr the user wants. I need to know what file to put it into and
it would be usefull to have the comment line returned (if any).

I did just get python essential reference 3rd edition.. If there is a
better reference on just the subject I am after I would be glad to grab
it when I get cash again.
Eric,

Tell us the story. Are you a student? A musician? What are you doing
with these files? Where do you get them from? What for?

Frederic
Eric,
I found an excellent CSound doc at:
ems.music.utexas.edu/program/mus329j/CSPrimer.pdf. I am myself
interested in music and will definitely look into this more closely.
For the time being I get the impression that you are dealing with
CSound instrument definition files which you can buy cheaply in great
quantity but unfortunately are illegibly formatted. If this is so, what
you would need is a formatter. I found references to CSound editors
(e.g. http://flavio.tordini.org/csound-editor/). Those should be capable
of formatting.
Writing your own formatter shouldn't be all that hard. Here's a
quick try:


def csound_formatter (in_file, out_file_file = sys.stdout):

INDENT = 10
CODE_LENGTH = 50

for l in in_file:
line = l.strip ()
if line == '':
out_file.write ('\n')
else:
if line [0] == ';': # Comment line
out_file.write ('%s\n' % line)
else:
code = comment = ''
if line [-1] == ':': # Label
out_file.write ('%s\n' % line)
else:
if ';' in line:
code, comment = line.split (';')
out_file.write ('%*s%-*s;%s\n' % (INDENT, '',
CODE_LENGTH, code, comment))
else:
out_file.write ('%*s%s\n' % (INDENT, '', line))


And here is a section of a csound file with white space squeezed out as
would make the file smaller:
Vibrato
; p4=amp p5=pch(fund) p6=vibdel p7=vibrate p8=vibwth
; p9=rise p10=decay p11=max index p12=car fac p13=modfac
; p14=index rise p15=index decay p16=left channel factor p17=original p3

instr 9,10,11,12
;--------------------------------------------------------------------------------
;initialization block:
kpitch init cpspch (p5)
itempo = p3/p17 ;ratio seconds/beats
idelay = p6 * itempo ;convert beats to secs
irise = p9 * itempo
idecay = p10 * itempo
indxris = (p14 == 0 ? irise : p14 * itempo)
indxdec = (p15 == 0 ? idecay : p15 * itempo)
if (p16 != 0) igoto panning ;if a panfac, use it, else
ilfac = .707 ;default is mono (sqrt(.5))
irfac = .707
igoto perform
panning:
ilfac = sqrt(p16)
irfac = sqrt(1-p16)
;--------------------------------------------------------------------------------
;performance block:
perform:
if (p7 == 0 || p8 == 0) goto continue
kontrol oscil1 idelay,1,.5,2 ;vib control
kvib oscili p8*kontrol,p7*kontrol,1 ;vibrato unit
kpitch = cpsoct(octpch(p5)+kvib) ;varying fund pitch in hz
continue:
kamp linen p4,irise,p3,idecay
kindex linen p11,indxris,p3,indxdec
asig foscili kamp,kpitch,p12,p13,kindex,1 ;p12,p13=carfac,mod fac
outs asig*ilfac,asig*irfac
endin
''')

Now we run this through the function defined above:

; Basic FM Instrument with Variable Vibrato
; p4=amp p5=pch(fund) p6=vibdel p7=vibrate p8=vibwth
; p9=rise p10=decay p11=max index p12=car fac p13=modfac
; p14=index rise p15=index decay p16=left channel factor p17=original p3

instr 9,10,11,12
;--------------------------------------------------------------------------------
;initialization block:
kpitch init cpspch (p5)
itempo = p3/p17 ;ratio
seconds/beats
idelay = p6 * itempo ;convert
beats to secs
irise = p9 * itempo
idecay = p10 * itempo
indxris = (p14 == 0 ? irise : p14 * itempo)
indxdec = (p15 == 0 ? idecay : p15 * itempo)
if (p16 != 0) igoto panning ;if a
panfac, use it, else
ilfac = .707 ;default is
mono (sqrt(.5))
irfac = .707
igoto perform
panning:
ilfac = sqrt(p16)
irfac = sqrt(1-p16)
;--------------------------------------------------------------------------------
;performance block:
perform:
if (p7 == 0 || p8 == 0) goto continue
kontrol oscil1 idelay,1,.5,2 ;vib control
kvib oscili p8*kontrol,p7*kontrol,1 ;vibrato unit
kpitch = cpsoct(octpch(p5)+kvib) ;varying
fund pitch in hz
continue:
kamp linen p4,irise,p3,idecay
kindex linen p11,indxris,p3,indxdec
asig foscili kamp,kpitch,p12,p13,kindex,1
;p12,p13=carfac,mod fac
outs asig*ilfac,asig*irfac
endin


It works on a couple of presumptions (e.g. no code following labels). So
it may not function perfectly but shouldn't be hard to tweak.

Hope this helps

Frederic
 
E

Eric_Dexter

Frederic said:
These are csound files. Csound recently added python as a scripting
language and is allowing also allowing csound calls from outside of
csound. The nice thing about csound is that instead of worrying about
virus and large files it is an interpiter and all the files look
somewhat like html. 4,000 virus free instruments for $20 is available
at
http://www.csounds.com and the csound programming book is also
available. The downside is that csound is can be realy ugly looking
(that is what I am trying to change) and it lets you write ugly looking
song code that is almost unreadable at times (would look nice in a
grid)

http://www.msn.com
..


Frederic said:
(e-mail address removed) wrote:

Frederic Rentsch wrote:


(e-mail address removed) wrote:


Frederic Rentsch wrote:



(e-mail address removed) wrote:



All I am after realy is to change this

reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces.. this is a corrected version from

http://python-forum.org/py/viewtopic.php?t=1703

thanks in advance the hole routine is down below..






Code:
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')                #opens file passed
in to read
f2 = open (output_File_Name, 'w')               #opens file passed
in to write
instr_yes = 'false'                             #set flag to false

for line in f:                                  #for through all
the lines
if "instr" in line:                           #look for instr in
the file
if instr_yes == 'true':                    #check to see if
this ends the instr block
break                                #exit the block

reline = re.line.split('instr', '/d$')     #error probily
split instr and /d (decimal number into parts) $ for end of line
number = int(reline[1])                  #convert to a
number maybe not important
if number == instr_number:            #check to see if
it is the instr passed to function
instr_yes = "true":                 #change flag to
true because this is the instr we want
if instr_yes = "true":                        #start of code to
copy to another file
f2.write(f.line)                         #write line to
output file

f.close                                         #close input file
f2.close





Eric,
From your problem description and your code it is unclear what
exactly it is you want. The task appears to be rather simple, though,
and if you don't get much useful help I'd say it is because you don't
explain it very well.
I believe we've been through this before and your input data is
like this

data = '''
<CsoundSynthesizer>;
; test.csd - a Csound structured data file

<CsOptions>
-W -d -o tone.wav
</CsOptions>

<CsVersion> ;optional section
Before 4.10 ;these two statements check for
After 4.08 ; Csound version 4.09
</CsVersion>

<CsInstruments>
; originally tone.orc
sr = 44100
kr = 4410
ksmps = 10
nchnls = 1
instr 1
a1 oscil p4, p5, 1 ; simple oscillator
out a1
endin
</CsInstruments>

<CsScore>
; originally tone.sco
f1 0 8192 10 1
i1 0 1 20000 1000 ;play one second of one kHz tone
e
</CsScore>

</CsoundSynthesizer>

Question 1: Is this your input?
if yes:
Question 1.1: What do you want to extract from it? In what format?
if no:
Question 1.1: What is your input?
Question 1.2: What do you want to extract from it? In what format?
Question 2: Do you need to generate output file names from the data?
(One file per instrument?)
if yes:
Question 2.1: What do you want to make your file name from?
(Instrument number?)


Regards

Frederic



I want to pass the file name to the subroutine and return a comment
string if it is there maybe it should be simplier. I probily should
have the option of grabbing the comment in other related routines. I
am pretty ambitious with the main program. I did notice some code in
tcl that would be usefull to the app If I compile it.. I am probily
not ready for that though..

http://www.dexrow.com




Eric,
I'm beginning to enjoy this. I'm sure we'll sort this out in no
time if we proceed methodically. Imagine you are a teacher and I am your
student. This is a quiz. I have to take it and you need to explain to me
the problem you want me to solve. If you don't explain it clearly, I
will not know what I have to do and cannot do the quiz. If you answer my
questions above, your description of the problem will be clear and I can
take the quiz. Okay?

Frederic


instr 1
a1 oscil p4, p5, 1 ; simple oscillator ; comment is
sometimes here
out a1
endin


I need to know the file I wan't to grab this from I need to grab this
out of the larger file and put it into it's own file, I need to know
what instr the user wants. I need to know what file to put it into and
it would be usefull to have the comment line returned (if any).

I did just get python essential reference 3rd edition.. If there is a
better reference on just the subject I am after I would be glad to grab
it when I get cash again.



Eric,

Tell us the story. Are you a student? A musician? What are you doing
with these files? Where do you get them from? What for?

Frederic
Eric,
I found an excellent CSound doc at:
ems.music.utexas.edu/program/mus329j/CSPrimer.pdf. I am myself
interested in music and will definitely look into this more closely.
For the time being I get the impression that you are dealing with
CSound instrument definition files which you can buy cheaply in great
quantity but unfortunately are illegibly formatted. If this is so, what
you would need is a formatter. I found references to CSound editors
(e.g. http://flavio.tordini.org/csound-editor/). Those should be capable
of formatting.
Writing your own formatter shouldn't be all that hard. Here's a
quick try:


def csound_formatter (in_file, out_file_file = sys.stdout):

INDENT = 10
CODE_LENGTH = 50

for l in in_file:
line = l.strip ()
if line == '':
out_file.write ('\n')
else:
if line [0] == ';': # Comment line
out_file.write ('%s\n' % line)
else:
code = comment = ''
if line [-1] == ':': # Label
out_file.write ('%s\n' % line)
else:
if ';' in line:
code, comment = line.split (';')
out_file.write ('%*s%-*s;%s\n' % (INDENT, '',
CODE_LENGTH, code, comment))
else:
out_file.write ('%*s%s\n' % (INDENT, '', line))


And here is a section of a csound file with white space squeezed out as
would make the file smaller:
Vibrato
; p4=amp p5=pch(fund) p6=vibdel p7=vibrate p8=vibwth
; p9=rise p10=decay p11=max index p12=car fac p13=modfac
; p14=index rise p15=index decay p16=left channel factor p17=original p3

instr 9,10,11,12
;--------------------------------------------------------------------------------
;initialization block:
kpitch init cpspch (p5)
itempo = p3/p17 ;ratio seconds/beats
idelay = p6 * itempo ;convert beats to secs
irise = p9 * itempo
idecay = p10 * itempo
indxris = (p14 == 0 ? irise : p14 * itempo)
indxdec = (p15 == 0 ? idecay : p15 * itempo)
if (p16 != 0) igoto panning ;if a panfac, use it, else
ilfac = .707 ;default is mono (sqrt(.5))
irfac = .707
igoto perform
panning:
ilfac = sqrt(p16)
irfac = sqrt(1-p16)
;--------------------------------------------------------------------------------
;performance block:
perform:
if (p7 == 0 || p8 == 0) goto continue
kontrol oscil1 idelay,1,.5,2 ;vib control
kvib oscili p8*kontrol,p7*kontrol,1 ;vibrato unit
kpitch = cpsoct(octpch(p5)+kvib) ;varying fund pitch in hz
continue:
kamp linen p4,irise,p3,idecay
kindex linen p11,indxris,p3,indxdec
asig foscili kamp,kpitch,p12,p13,kindex,1 ;p12,p13=carfac,mod fac
outs asig*ilfac,asig*irfac
endin
''')

Now we run this through the function defined above:

; Basic FM Instrument with Variable Vibrato
; p4=amp p5=pch(fund) p6=vibdel p7=vibrate p8=vibwth
; p9=rise p10=decay p11=max index p12=car fac p13=modfac
; p14=index rise p15=index decay p16=left channel factor p17=original p3

instr 9,10,11,12
;--------------------------------------------------------------------------------
;initialization block:
kpitch init cpspch (p5)
itempo = p3/p17 ;ratio
seconds/beats
idelay = p6 * itempo ;convert
beats to secs
irise = p9 * itempo
idecay = p10 * itempo
indxris = (p14 == 0 ? irise : p14 * itempo)
indxdec = (p15 == 0 ? idecay : p15 * itempo)
if (p16 != 0) igoto panning ;if a
panfac, use it, else
ilfac = .707 ;default is
mono (sqrt(.5))
irfac = .707
igoto perform
panning:
ilfac = sqrt(p16)
irfac = sqrt(1-p16)
;--------------------------------------------------------------------------------
;performance block:
perform:
if (p7 == 0 || p8 == 0) goto continue
kontrol oscil1 idelay,1,.5,2 ;vib control
kvib oscili p8*kontrol,p7*kontrol,1 ;vibrato unit
kpitch = cpsoct(octpch(p5)+kvib) ;varying
fund pitch in hz
continue:
kamp linen p4,irise,p3,idecay
kindex linen p11,indxris,p3,indxdec
asig foscili kamp,kpitch,p12,p13,kindex,1
;p12,p13=carfac,mod fac
outs asig*ilfac,asig*irfac
endin


It works on a couple of presumptions (e.g. no code following labels). So
it may not function perfectly but shouldn't be hard to tweak.

Hope this helps

Frederic

I was hoping to add and remove instruments.. although the other should
go into my example file because it will come in handy at some point.
It would also be cool to get a list of instruments along with any
comment line if there is one into a grid but that is two different
functions.

http://www.dexrow.com
 
F

Frederic Rentsch

snip snip snip snip snip .........
I was hoping to add and remove instruments.. although the other should
go into my example file because it will come in handy at some point.
It would also be cool to get a list of instruments along with any
comment line if there is one into a grid but that is two different
functions.

http://www.dexrow.com

Eric,

Below the dotted line there are two functions.
"csound_filter ()" extracts and formats instrument blocks from
csound files and writes the output to another file. (If called without
an output file name, the output displays on the screen).
The second function, "make_instrument_dictionaries ()", takes the
file generated by the first function and makes two dictionaries. One of
them lists instrument ids keyed on instrument description, the other one
does it the other way around, listing descriptions by instrument id.
Instrument ids are file name plus instrument number.
You cannot depend on this system to function reliably, because it
extracts information from comments. I took my data from
"ems.music.utexas.edu/program/mus329j/CSPrimer.pdf" the author of which
happens to lead his instrument blocks with a header made up of comment
lines, the first of which characterizes the block. That first line I use
to make the dictionaries. If your data doesn't follow this practice,
then you may not get meaningful dictionaries and are in for some
hacking. In any case, this doesn't look like a job that can be fully
automated. But if you can build your data base with a manageable amount
of manual work you should be okay.
The SE filter likewise works depending on formal consistency with
my sample. If it fails, you may have to either tweak it or move up to a
parser.
I'll be glad to provide further assistance to the best of my
knowledge. But you will have to make an effort to express yourself
intelligibly. As a matter of fact the hardest part of proposing
solutions to your problem is guessing what your problem is. I suggest
you do this: before you post, show the message to a good friend and edit
it until he understands it.

Regards

Frederic
..

------------------------------------------------------------------------------------------------------------------------

def csound_filter (csound_file_name,
name_of_formatted_instrument_blocks_file = sys.stdout):

"""
This function filters and formats instrument blocks out of a
csound file.

csound_formatter (csound_file_name,
name_of_formatted_instrument_blocks_file)
csound_formatter (csound_file_name) # Single argument: screen output

"""

import SE
Instruments_Filter = SE.SE ('<EAT> "~;.*~==(10)"
"~instr(.|\n)*?endin~==(10)(10)"')

INDENT = 10
CODE_LENGTH = 50

def format ():
for l in instruments_file:
line = l.strip ()
if line == '':
out_file.write ('\n')
else:
if line [0] == ';': # Comment line
out_file.write ('%s\n' % line)
else:
code = comment = ''
if line [-1] == ':': # Label
out_file.write ('%s\n' % line)
else:
if ';' in line:
code, comment = line.split (';')
out_file.write ('%*s%-*s;%s\n' % (INDENT, '',
CODE_LENGTH, code, comment))
else:
out_file.write ('%*s%s\n' % (INDENT, '', line))

instruments_file_name = Instruments_Filter (csound_file_name)
instruments_file = file (instruments_file_name, 'w+a')
if name_of_formatted_instrument_blocks_file != sys.stdout:
out_file = file (name_of_formatted_instrument_blocks_file, 'wa')
owns_out_file = True
else:
out_file = name_of_formatted_instrument_blocks_file
owns_out_file = False

format ()

if owns_out_file: out_file.close ()



def make_instrument_dictionaries (name_of_formatted_instrument_blocks_file):

"""
This function takes a file made by the previous function and
generates two dictionaries.
One records instrument ids by description. The other one
instrument descriptions by id.
Instrument ids are made up of file name and instrument number.
If these two dictionaries are pickled they can be used like data
bases and added to
incrementally.

"""

import re
instrument_numbers_re = re.compile ('instr *([0-9,]+)')

in_file = file (name_of_formatted_instrument_blocks_file, 'ra')

instrument_descriptions_by_id = {}
instrument_ids_by_description = {}

inside = False
for line in in_file:
line = line.strip ()
if not inside:
if line:
instrument_description = line [1:].rstrip ()
inside = True
else:
if line == '':
inside = False
if inside:
if line.startswith ('instr'):
instrument_numbers = instrument_numbers_re.match
(line).group (1).split (',')
instrument_ids = ['%s: %s' %
(name_of_formatted_instrument_blocks_file, i_n) for i_n in
instrument_numbers]
instrument_ids_by_description [instrument_description] =
instrument_ids
for instrument_id in instrument_ids:
instrument_descriptions_by_id [instrument_id] =
instrument_description

in_file.close ()

return instrument_descriptions_by_id, instrument_ids_by_description

---------------------------------------------------------------------------------------------
print '%s - %s' % (instrument_id,
instrument_descriptions_by_id [instrument_id])

T:\instruments: 5 - Simple Gating Instrument with Chorus
T:\instruments: 4 - Portamento/Panning Instrument
T:\instruments: 12 - Basic FM Instrument with Variable Vibrato
T:\instruments: 11 - Basic FM Instrument with Variable Vibrato
T:\instruments: 10 - Basic FM Instrument with Variable Vibrato

---------------------------------------------------------------------------------------------
print description
for instrument in instrument_ids_by_description [description]:
print ' ', instrument

Basic FM Instrument with Variable Vibrato
T:\instruments: 9
T:\instruments: 10
T:\instruments: 11
T:\instruments: 12
Simple Gating Instrument with Chorus
T:\instruments: 5
T:\instruments: 6
T:\instruments: 7
T:\instruments: 8
Portamento/Panning Instrument
T:\instruments: 1
T:\instruments: 2
T:\instruments: 3
T:\instruments: 4

---------------------------------------------------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top