need help extracting data from a text file

Iain King iainking at gmail.com
Mon Nov 7 16:49:10 CET 2005


nephish at xit.net wrote:
> Hey there,
> i have a text file with a bunch of values scattered throughout it.
> i am needing to pull out a value that is in parenthesis right after a
> certain word,
> like the first time the word 'foo' is found, retrieve the values in the
> next set of parenthesis (bar) and it would return 'bar'
>
> i think i can use re to do this, but is there some easier way?
> thanks

well, you can use string.find with offsets, but an re is probably a
cleaner way to go.  I'm not sure which way is faster - it'll depend on
how many times you're searching compared to the overhead of setting up
an re.

start = textfile.find("foo(") + 4     # 4 being how long 'foo(' is
end = textfile.find(")", start)
value = textfile[start:end]

Iain




More information about the Python-list mailing list