Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Suppose I have a file with multiple tables, each separated by a line beak, like this:

banana yellow
apple red
grape purple

fire red
water blue
sky blue

parrot green
whale blue
cat yellow

I need to create three lists of ordered pairs out of this single file. If I had just a single table, I'd simply use data = Import["file.dat", "Table"], but in this case I don't know how to tell Mathematica to split into three tables and that I need a data1, a data2 and a data3.

share|improve this question

2 Answers 2

This is one way:

str = "banana yellow
 apple red
 grape purple

 fire red
 water blue
 sky blue

 parrot green
 whale blue
 cat yellow";

DeleteCases[SplitBy[ImportString[str, "Table"], # === {} &], {{}}]

(* ==>

{{{"banana", "yellow"}, {"apple", "red"}, {"grape", "purple"}}, 
 {{"fire", "red"}, {"water", "blue"}, {"sky", "blue"}}, 
 {{"parrot", "green"}, {"whale", "blue"}, {"cat", "yellow"}}}

*)
share|improve this answer

I like Szabolcs'solution better, but here is my alternative:

str = "banana yellow
apple red
grape purple

fire red
water blue
sky blue

parrot green
whale blue
cat yellow";

ImportString[#, "Table"] & /@ StringSplit[ImportString[str, "String"], "\n\n"]

(* {{{"banana", "yellow"}, {"apple", "red"}, {"grape", "purple"}}, 
    {{"fire", "red"}, {"water", "blue"}, {"sky", "blue"}}, 
    {{"parrot", "green"}, {"whale", "blue"}, {"cat", "yellow"}}} *)

Note that the rightmost ImportString stands for the Import that you would normally do to import a file (the ImportString is used here for demonstration purposes, so that no external file is needed). The leftmost ImportString should be exactly as it is.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.