Mathematica: how to read files?

  • Context: Mathematica 
  • Thread starter Thread starter nenyan
  • Start date Start date
  • Tags Tags
    files Mathematica
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 7K views
nenyan
Messages
67
Reaction score
0
reading data from txt files
there are two .txt files. One is map.txt, another is event.txt.

map looks like below:

dfafdafskdjf:{{0.837711763427 -0.8359730469 2.4152891949e-04 0.000360245716236} {0.831761777387 -0.8240730748 2.4446745066e-04 0.000359914513716} {0.819861805217 -0.8062231165 2.4910805126e-04 0.000359863615611}} klsajlkf

What I need are data in {}, omited the begging srting and the endding string.


event.txt:
PGC | Name | RA | Dec | Type | App_Mag | Maj_Diam (a) | err_Maj_Diam | Min_Diam (b) | err_Min_Diam | b/a | err_b/a | PA | Abs_Mag | Dist | err_Dist | err_App_Mag | err_Abs_Mag |

2|UGC12889|0.00047|47.27450|3.1|13.31|1.546|0.498|1.314|~|0.85|0.100|~|-21.05|72.458|10.869|0.61|0.61|
4|PGC000004|0.00096|23.08764|5.0|15.39|0.851|0.078|0.186|~|0.219|0.015|~|-18.68|63.264|13.918|0.39|0.40|
...
...


How to read these two files by mathematica? Thanks.
 
Physics news on Phys.org
Perhaps this will get you started

In[1]:= stream=OpenRead["map.txt"];
allwords="";
While[(word=Read[stream,Record])=!=EndOfFile,
word=StringReplace[word,RegularExpression["[a-z:]*"]->""];
allwords=StringJoin[allwords,word];
];
Close[stream];
Print[allwords];

From In[1]:=
{{0.837711763427 -0.8359730469 2.4152891949-04 0.000360245716236} \
{0.831761777387 -0.8240730748 2.4446745066-04 \
0.000359914513716}{0.819861805217 -0.8062231165 2.4910805126-04 \
0.000359863615611}}

Now you will need to position your map.txt file in the appropriate place or you will have to give a path to the OpenRead.
Notice this has "eaten" your 'e' in your exponential form because the regular expression is eliminating alphabetic characters, and colons. But you would have needed to find a way to correctly translate your exponents into a Mathematica format anyway and this will just give you a little more practice. Notice you do not have commas between your }{ in your input and this will make it a little more difficult to have Mathematica easily translate this as a single simple expression using ToExpression.

This should give you an idea how to get started. Look up RegularExpression in Mathematica for more information. If you get stuck then show how much you have figured out and just where you are stuck and someone can provide more pointers.