Jump to content


Photo

Reading Columns from a Text file.


  • Please log in to reply
2 replies to this topic

#1 vidyashankara

vidyashankara
  • Members
  • PipPipPip
  • Advanced Member
  • 75 posts

Posted 14 June 2006 - 11:41 PM

Lets say i have a text file. It contains

ATOM 1009 N L U A 163 37.984 -12.158 -19.748 1.00 78.45
ATOM 2700 CG ASP B  164 82.383 0.302 48.606 1.00110.37     
ATOM 2701 OD1 ASP B  168 82.019 0.628 49.756 1.00110.37    

I want the script to count the Number of A or B in the 5th column.

Currently i exploded the file into lines and i called it with a for function to read the 5th column. The code is

$array = explode("\n",atom.txt);
for ($i=0; $i<count($array); $i++) {
   preg_match_all("/([^ \r\n]+)(?:[ ]+)*/", $array[$i], $n);
   $atom[$i] = $n[1];
   $atoms[$i] = $n[1][3];    
}

$atoms = array_unique($atoms);
sort($atoms);

This does the job. But if you look carefully at the text file, it contains lines like

ATOM   1009  N   L U A 163      37.984 -12.158 -19.748  1.00 78.45           N  

Where A is not the 5th column but the 6th, There is a space between L and U. In this case, It select U instead of A and reports it, which is wrong.

Can i make the script read from the 21st column of the text file? (each letter is in one column)

How do i do that?

Thanks
Vidyashankra.

#2 dkphp2

dkphp2
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 14 June 2006 - 11:47 PM

That would be even easier, use substr():

substr($str, 21, 1); // this gives you the 21st character for each line.

#3 vidyashankara

vidyashankara
  • Members
  • PipPipPip
  • Advanced Member
  • 75 posts

Posted 15 June 2006 - 12:06 AM

[!--quoteo(post=384027:date=Jun 14 2006, 06:47 PM:name=dkphp2)--][div class=\'quotetop\']QUOTE(dkphp2 @ Jun 14 2006, 06:47 PM) View Post[/div][div class=\'quotemain\'][!--quotec--]
That would be even easier, use substr():

substr($str, 21, 1); // this gives you the 21st character for each line.
[/quote]


Thanks a lot! that did the job. so simple!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users