View this PageEdit this PageUploads to this PageHistory of this PageTop of the SwikiRecent ChangesSearch the SwikiHelp Guide

parsing text files



//a Textfile parser utility class
//jrh 2002 with help by epic

Text  {
	var <>string;
	*new { arg string;
		^super.new.string_(string);
	}
	
	separate { arg func;
		var array, indices,  i0= -1;
		array = [];
		indices = [];
		string.do({ arg char, i;
			if(func.value(char,  i), {
				indices = indices.add(i);
			});
		});
		indices = indices.add(string.size-1);
		(indices.size - 1).do({ arg i;
			var substring;
			substring = string.copyRange(i0+1, indices.at(i)-1);
			i0 = indices.at(i);
			array = array.add(substring);
		});
		array = array.add(string.copyRange(i0+1, string.size-1));
		
		^array;
	
	}
	
	stringToFloat { arg string;
		string = string.select({ arg char; char.isDecDigit || (char == $.) });
		^string.interpret;
	}
	replace { arg that, by;
		string = string.collect({ arg char; if(char == that ,{ by }, {char}) });
	}
	
	convertDecimalCommas {
		this.replace($, ,$. )
	}
	
	asSignal { arg delimiterFunc;
		var signal, substring, float;
		
		delimiterFunc = delimiterFunc ?? {{arg char; char !== Char.blank}};
		signal = Signal(512);
		substring = String.new;
		string.do({ arg char;
			
			if(delimiterFunc.value.not, { 
				substring = substring ++ char;
			}, {
				float = this.stringToFloat(substring);
				if(float.notNil, { signal = signal.add(float) });
				substring = String.new;
			});
		});
		float = this.stringToFloat(substring);
		if(float.notNil, { signal = signal.add(float) });
		
		^signal;
	}

}

______
//test: extract all numbers out of a text and convert it to a signal
var file, signal, text;
GetFileDialog({ arg ok, path;
	if(ok, { 
		file = File(path, "rb");
		text = Text(file.readAllString);
		text.convertDecimalCommas;
		signal = text.asSignal.asCompileString.postln;
    file.close;
	})
});






Links to this Page