473,434 Members | 1,807 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,434 software developers and data experts.

need help extracting data from a text file

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

Nov 7 '05 #1
7 1529

ne*****@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

Nov 7 '05 #2
this is cool, it is only going to run about 10 times a day,

the text is not written out like foo(bar) its more like
foo blah blah blah (bar)

the thing is , every few days the structure of the textfile may change,
one of the reasons i wanted to avoid the re.

thanks for the tip,

Nov 7 '05 #3

ne*****@xit.net wrote:
this is cool, it is only going to run about 10 times a day,

the text is not written out like foo(bar) its more like
foo blah blah blah (bar)


then I guess you worked this out, but just for completeness:

keywordPos = textfile.find("foo")
start = textfile.find("(", keywordPos)
end = textfile.find(")", start)
value = textfile[start:end]
Iain

Nov 7 '05 #4
um, wait. what you are doing here is easier than what i was doing after
your first post.
thanks a lot. this is going to work out ok.

thanks again.
sk

Nov 7 '05 #5
<ne*****@xit.net> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
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

Using string methods to locate the 'foo' instances is by far the fastest way
to go.

If your requirements get more complicated, look into using pyparsing
(http://pyparsing.sourceforge.net). Here is a pyparsing rendition of this
problem. This does three scans through some sample data - the first lists
all matches, the second ignores matches if they are found inside a quoted
string, and the third reports only the third match. This kind of
context-sensitive matching gets trickier with basic string and re tools.

-- Paul

data = """
i have a text file with a bunch of foo(bar1) values scattered throughout it.
i am needing to pull out a value that foo(bar2) is in parenthesis right
after a
certain word,
like the foo(bar3) first time the word 'foo' is found, retrieve the values
in the
next set of parenthesis foo(bar4) and it would return 'bar'
do we want to skip things in quotes, such as 'foo(barInQuotes)'?
"""

from pyparsing import Literal,SkipTo,quotedString

pattern = Literal("foo") + "(" + SkipTo(")").setResultsName("payload") + ")"

# report all occurrences of xxx found in "foo(xxx)"
for tokens,start,end in pattern.scanString(data):
print tokens.payload, "at location", start
print

# ignore quoted strings
pattern.ignore(quotedString)
for tokens,start,end in pattern.scanString(data):
print tokens.payload, "at location", start
print

# only report 3rd occurrence
tokenMatch = {'foo':0}
def thirdTimeOnly(strg,loc,tokens):
word = tokens[0]
if word in tokenMatch:
tokenMatch[word] += 1
if tokenMatch[word] != 3:
raise ParseException(strg,loc,"wrong occurrence of token")

pattern.setParseAction(thirdTimeOnly)
for tokens,start,end in pattern.scanString(data):
print tokens.payload, "at location", start
print

Prints:
bar1 at location 36
bar2 at location 116
bar3 at location 181
bar4 at location 278
barInQuotes at location 360

bar1 at location 36
bar2 at location 116
bar3 at location 181
bar4 at location 278

bar3 at location 181
Nov 7 '05 #6
ne*****@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?


It's pretty easy with an re:
import re
fooRe = re.compile(r'foo.*?\((.*?)\)')
fooRe.search('foo(bar)').group(1) 'bar' fooRe.search('This is a foo bar baz blah blah (bar)').group(1)

'bar'

Kent
Nov 7 '05 #7
On Mon, 7 Nov 2005, Kent Johnson wrote:
ne*****@xit.net wrote:
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'


It's pretty easy with an re:
import re
fooRe = re.compile(r'foo.*?\((.*?)\)')
Just out of interest, i've never really got into using non-greedy
quantifiers (i use them from time to time, but hardly ever feel the need
for them), so my instinct would have been to write this as:
fooRe = re.compile(r"foo[^(]*\(([^)]*)\)")
Is there any reason to use one over the other?
fooRe.search('foo(bar)').group(1) 'bar' fooRe.search('This is a foo bar baz blah blah (bar)').group(1)

'bar'


Ditto.

tom

--
[of Muholland Drive] Cancer is pretty ingenious too, but its best to
avoid. -- Tex
Nov 9 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Trader | last post by:
Hi, I'm trying to use Mark Hammond's win32clipboard module to extract more complex data than just plain ASCII text from the Windows clipboard. For instance, when you select all the content on...
5
by: Michael Hill | last post by:
Hi, folks. I am writing a Javascript program that accepts (x, y) data pairs from a text box and then analyzes that data in various ways. This is my first time using text area boxes; in the past,...
2
by: Kevin K | last post by:
Hi, I'm having a problem with extracting text from a Word document using StreamReader. As I'm developing a web application, I do NOT want the server to make calls to Word. I want to simply...
16
by: Preben Randhol | last post by:
Hi A short newbie question. I would like to extract some values from a given text file directly into python variables. Can this be done simply by either standard library or other libraries? Some...
4
by: georges the man | last post by:
hey guys, i ve been posting for the last week trying to understand some stuff about c and reading but unfortunaly i couldnt do this. i have to write the following code. this will be the last...
6
by: Mag Gam | last post by:
Hi All, I am new to XML, and trying to extract some data from a file. The file looks like this: <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST>...
0
by: sgsiaokia | last post by:
I need help in extracting data from another source file using VBA. I have problems copying the extracted data and format into the required data format. And also, how do i delete the row that is not...
3
by: Clarisa | last post by:
Hello Folks I am working on extracting lines of data in a text file based on the string it contains. This is the text file called info.txt:
6
by: Werner | last post by:
Hi, I try to read (and extract) some "self extracting" zipefiles on a Windows system. The standard module zipefile seems not to be able to handle this. False Is there a wrapper or has...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.