MathGroup Archive 2003

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: How to read a certain number from a file?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg42170] Re: How to read a certain number from a file?
  • From: Bill Rowe <listuser at earthlink.net>
  • Date: Sat, 21 Jun 2003 02:49:44 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

On 6/20/03 at 4:57 AM, quake_earthNOSPAM at hotmail.com (cyberdude) wrote:

> Suppose I have the following text file (file name is abc.txt):
> 
> ....................................................
> ...... 3 children ....... he carries 2 .............
> ....................................................
> 
> If I am given the words 'children' and 'he carries' but no other words and
> it is assumed that they appear only once in the file, how can I extract the
> numbers '3' and '2' which are next to these words in the file and put them
> into two variables with Mathematica? 

The only sure way I know given *only* the information you've indicated is to do something along the line of

data = ReadList["abc.txt", Word];
a = Position[data, "children"][[1,1]];
result1 = ToExpression[data[[a-1]]]
a = Position[data, "carries"][[1,1]];
result2 = ToExpression[data[[a+1]]]

Given more information this can be made much more elegant. Possibly a single call to ReadList could be made to extract just the information you want.

Note, what I've outlined above does make a few assumptions about the file "abc.txt" beyond what is stated. Specifically, I've assumed there is no occurance of the words "children" and "carries" in the file before the target numbers. 

If I assume both of the target numbers occur on the same line as suggested by your post, then FindList["abc.txt","children", 1] will extract only the first line with the word "children" reducing the amount of data being read. Then you could use StringPosition to locate the positions of "children" and "he carries" within the string and use this with StringTake to pass the portion of the string containing the data to ToExpression.


  • Prev by Date: Re: variogram
  • Next by Date: Re: InverseFunction[]
  • Previous by thread: How to read a certain number from a file?
  • Next by thread: Appending data to a existing file