Loading...
Logo
Processing Forum
I can load .txt files using, for example:

String lines[] = loadStrings("text.txt");

No problem. I can easily load complete words, but I don't want to load a complete word, I want to load only the individual characters from a word.

I have a poem I'm trying to read into Processsing, and then convert each word into a number, I'm thinking, to keep it simple: once I have each letter, I'll get its ASCII code, but I can't even figure out how to load only one letter at a time from a word.

I have 48 text files supplied to me, of the same poem with variations from the 16th century, and I would like to compare the variations between the poems.

My plan is to start simple, load two text files, two words each, and then figure out a way to load each letter from each word.
That's where I'm stuck.

This code will load the first two lines of a text file, but I can only get the number of lines, and then complete words, I can't figure out how to break the words into individual letters.

I imagine it's probably very simple, help, please?

Please note that I don't know how to use the charAt() code to read from an imported .txt file, only from a String from within the Sketch, and I really don't want to type in all of the supplied poems, or convert the words to ASCII myself, though I could... sigh. I'd rather learn how to break an imported word into its constituent letters.


char letter;
String elegy = "Come, madam";


void setup() {
  size(100, 100);

  String lines[] = loadStrings("come_madam.txt");
    println("there are " + lines.length + " lines");
// use 'e' for 'elegy' for the integer variable in the for loop
    for (int e = 0; e < lines.length; e++) {
      String[] words = split(lines[e], ' ');
 
  letter = elegy.charAt(4);
  println(lines[e]);
  println(words);
  println(lines[e].length());
  println(letter);

      }
}

This code will correctly read in the practice lines from a .txt file named come_madam.txt (Elegy 8 by John Donne)
and show in the console that I am getting line counts and complete words. Now, how to break those words, or how to import single characters? Is there some way to use 'split' that will cut at each character?

Thanks,
Scotrick

Replies(24)

Hmm this gets pretty hairy with loops because you cant pass in an empty char into the split. I did it with embedding a double for loop through the words array to get each letter from each word.There may be a faster way but this worked for me:

Copy code
  1. char letter;
  2. String elegy = "Come, madam";
  3. void setup() {
  4.   size(100, 100);
  5.   String lines[] = loadStrings("come_madam.txt");
  6.     println("there are " + lines.length + " lines");
  7. // use 'e' for 'elegy' for the integer variable in the for loop
  8.     for (int e = 0; e < lines.length; e++) {
  9.       String[] words = split(lines[e], ' ');
  10.       for(int i = 0; i< words.length; i++){
  11.         for(int j = 0; j<words[i].length(); j++){
  12.           char let = words[i].charAt(j);
  13.           println(let);
  14.         }
  15.       }
  16.  
  17.   letter = elegy.charAt(4);
  18.   println(lines[e]);
  19.   println(words);
  20.   println(lines[e].length());
  21.   println(letter);
  22.       }
  23. }
Copy code
  1. String elegy = "Come, madam";
  2. char[] chars = elegy.toCharArray();
  3. println(chars);

Hi, Kobby, thanks for the code. I had actually tried that method, but got tangled up in the loops myself, and I couldn't figure out the key thing that you did, which was to have both the words[] array and then combine that with the search for charAt.

I'll give that a whirl and see how it goes. Thanks a bunch.

PhiLho, while I appreciate what you're written, if you look at my example code, I already have figured out how to pull characters from a string from within a Processing sketch. How would you modify your code so that it pulls single characters from an external .txt file? Again, it's probably dense of me not to see how to modify your suggestion to apply to text loaded from a file, but that's definitely where I've been stuck: externally loaded .txt files read into Processing.

And, of course I could alter the .txt files in some manner, such as putting a space after each letter and then a tab after each word, or some such, but that would mean seriously altering 48 long .txt files that are 'standards' in this particular niche study of this poem by Donne. So, if I can load in a .txt file that most closely resembled what I've been given to work with, it'll be more useful to other people working on the same project, because they'll be able to use their own copies of the Donne poems as references.

PhiLho, I'll try and adapt your code to apply to a loaded .txt, and report back if I fail. Which is likely. :)
But many thanks to both of you, and of course, if I get this working, I'll post it back here, however inelegant it might be.

Scotrick


No problem, but actually, once you have done loadStrings(), you already made the step from the file to strings.
You can apply the method on each item in the array.
Now, chatAt() is fine too. I just shown how to have the equivalent of a split between letters...
PhiLho -

Thanks (and of course, to the answer above) but I am being really dense somehow. I even managed to trace back to a discussion you had about using the Java character iterator where you gave some good advice.

Here's my problem. Somehow I don't get the transition from text assigned to a String from with the Sketch, like:
String elegy = "Come, madam";

And then how you manage to apply the same coding principles here:

String elegy = "Come, madam";
char[] chars = elegy.toCharArray();
println(chars);

To one where the text is coming from a loaded text file, for example:

 String lines[] = loadStrings("come_madam.txt");
   chars = lines.toCharArray();
  println(chars);

Obviously, I'm missing a line where something, perhaps lines[], gets turns into an array, or something.
The error the above code generates is 'Cannot invoke toCharArray() on the array type String[]

Which makes me think I'm missing a crucial step where what I import is assigned to a variable, but I'm not sure how or what's happening. I know I've already taken up plenty of your time, and FYI there's another solution to this problem in the book "Learning Processing" example 18, but prefer the one you've proposed, so I'm hoping to learn how to make it work.

Eventually, I want to make a program that will take each word of a poem, convert it to its individual letters, convert those to ASCII, add them up, and thus create a number for each word based on its ASCII content. The reason I want numbers rather than a simple string to string comparison is that I want to use those numbers to graphically display difference between words in the same poem. Does that make sense? Am I going about this a backwards difficult way?

Thanks again, for all of your time and energy,
Scotrick
OK, y'all. Thank you for your help so far, and I thought I would create the simplest program I could, one that would load one word from a .txt file, a single word, and then print it to the screen, across a grid.
The following program manages to do this. As you can see from my opening comments, my next plan is to learn how to turn that word into a number, and then compare that number with other numbers.

What do you think so far, am I still going about this the right way? Thanks so much you two, I couldn't have made it this far without either of you. I apologize for my excessive commenting, as that's the only way I can keep track of where I am and what's going on.

As you'll see from my comments, I'm only just getting started, and any advice about where I might be going wrong, would be helpful, otherwise, I'll keep plugging along, and posting here, in case anyone else is interested in a similar thing.


// Scotrick with help from programmers on the Processing forum, PhiLho and Kobby
// and concepts and code from 'learning processing'
// This is the only part I've managed to accomplishg so far, to load a word from a .txt file.
// and print it across a grid.                                                                                                      
// a program to parse from a .txt file a word and assign each letter an ASCII value             I haven't managed this part yet
// then combine those values to get a numberical value for the entire word,                        or this part
// ideally, not just the ASCII value of the word, but its position in the order of words.
//
// If this step is accomplished, then more words will be added to the array,
// and hopefully compared.

// create integer variables to store the stage width and height in columns and rows
  int columns, rows;

// create integer variables to store the width and height of the stage
  int wide, high;
 
// the 'Pfont' variable to hold the standard font variable 'f'
  PFont f;

// begin the function setup()

void setup() {

// to create a grid for the letters of the complete poem, with each square being 10 pixels by 10 pixels
  size(960, 840);
 // Load the font
  f = createFont("Candara-Bold-12.vlw", 12, true);
 

// using similar designations as to that from the 'Game of Life'
// I hope to use a similar grid to help sort out the words and lines of the poem
// as a starting point
  columns = width;
  rows = height;
  wide = width;
  high = height;
 
  String lines[] = loadStrings("come.txt");
  println("there are " + lines.length + " lines");
// use 'e' for 'elegy' for the integer variable in the for loop
  for (int e = 0; e < lines.length; e++)
  {
    String[] words = split(lines[e], ' ');
        for(int i = 0; i < words.length; i++)
          {
            for(int j = 0; j <words[i].length(); j++)
              {
                char let = words[i].charAt(j);
                println(let);
              }
          }
         
   
    
      println(words);
      println(lines[e]);
      println(lines[e].length());
      println("let");

  }
// creates the background color of very light blue 
background(219, 243, 241);

}


// begin the function draw()
   
void draw() {
 
// assign the textFont 'f'
  textFont(f, 10);
  text(("words"), 20, 50);

    {

// call the function that creates a grid on the stage of the Sketch 
    drawGrid(wide, high);

    }
   
}


///////////////////////////////////////////////////////////////////////
// divides the functions from the main program areas
///////////////////////////////////////////////////////////////////////
   
// function 'drawGrid' simply draws a light colored grid on the 'stage'
void drawGrid(int wide, int high)
  {
// set a background of lines
  for (int x = 0; x < wide; x += 10)
  {
    for (int y = 0; y < high; y += 10)
    {
// sets the stroke color
      stroke(200, 200, 200);
// sets the strokeWeight
      strokeWeight(1);
// draws the vertical lines
      line(x, y, x, high);
// sets the stroke color to light gray
      stroke(30, 30, 30);
// sets the strokeWeight
      strokeWeight(1);
// draws the horizontal lines
      line(x, y, wide, y);
    }
  }
}
Mmm, I supposed you knew how to do it, since you access each string in the code you shown initially, and Kobby used the same technique...
Copy code
  1. String lines[] = loadStrings("come_madam.txt");
  2. for (int e = 0; e < lines.length; e++) {
  3.   String line = lines[e]; // Take one element of the array, one line
  4.   char[] chars = line.toCharArray(); // Split the line into chars
  5. }
Or split the line into words as you did, and apply toCharArray() to each word.
Thanks PhiLho, it took me a sadly long time to adjust the code from Kobby and the code you gave me and get the result I posted.

In my example, it took me forever to figure out that I needed to put the " around the word "words" in my text line.
So, your example really helps. I'm one of those people that needs to see something as many different ways as I can before any of it sinks in, so I really appreciate it.

I don't know where you are in the world, but I'm in Virginia where it's 4:43am, because I've been up all night trying to overcome my own slowness when it comes to working with strings.

I hope I can get some sleep eventually. :) These kinds of problems tend to keep me awake. I'm boring that way.
And I really can't thank you enough.
Scotrick
Well, drat, the code I posted above doesn't really work. It should print the word 'come' on the grid, but instead simply prints the word 'words'.

How do I pull the variable that holds the word from the array down into the draw so that I can display each word of the poem? I keep getting this error, cannot find anything named 'words', which makes me think it's because the variables are in the setup and not in the draw function. Is that right?

And yet, other versions of this same concept somehow get around this. Dang it.
" which makes me think it's because the variables are in the setup and not in the draw function"
Probably... You need to declare global variables so that they can be shared between these functions. See the What are setup() and draw()? article...
Our help can be more precise if you show the current state of your code...
Ah, dear PhiLho, that was the current state of my code. I think you're right, and I was just double checking, so the first thing I will do is try a global variable set.

Cheers. :)
For PhiLho, or anyone, the code below is where I'm at now. I took PhiLho's excellent suggestion, which I had also pondered as a possible solution, which was to put the variable I'm trying to display on the stage of the Sketch outside of the setup() so that it was a global variable.

In this case, that variable's name is 'words', and should only be displaying one word: come.
However, as you can see if you run the code, it doesn't give me an error any more about the variable, as I made it a global variable, but also, nothing appears on the screen. To make sure I was getting a screen display, I also added a control word to display, the same variable as a string, further down than where my 'words' variable should appear.

I also tried removing my grid function, in case it was somehow interfering in the display of the word, and still, no dice.
I don't know what's preventing this word from showing up. In case you want to try this, the .txt literally contains only one word, Come, and of course, any font can be used, right?

Also, all of my println calls return to the console the information I'm seeking, including that the 'words' variable contains the word, come. I feel like perhaps I should be calling the array of the first [0] cell, which is the cell that contains the word come, but I don't know if that instinct is right. At any rate, that is the next thing I'm going to try.

And re PhiLho's advice, this is the last code I have that works at all.
Thanks again, you guys. I'm beating my head against the table on this one, because I feel it should be something so simple, and yet I'm not able to figure it out. I came from programming using ActionScript 3.0, and the switch is making me batty.



// Scotrick - with help from programmers on the Processing forum, PhiLho and Kobby,
// as well as help from the book, 'learning processing' example 18-6, parsing King Lear.
//
// This hopefully will be a program to parse from a .txt file a word and assign each letter an ASCII value
// then combine those values to get a numerical value for the entire word,
// ideally, not just the ASCII value of the word, but its position in the order of words.
//
// If this step is accomplished, then more words will be added to the array,
// and hopefully compared.

// create integer variables to store the stage width and height in columns and rows
  int columns, rows;

// create integer variables to store the width and height of the stage
  int wide, high;
 
// create the string variable
  char words;
 
// create the string variable
  char let;
   
// the 'Pfont' variable to hold the standard font variable 'f'
  PFont f;

// begin the function setup()

void setup() {

// to create a grid for the letters of the complete poem, with each square being 10 pixels by 10 pixels
  size(960, 840);
// load the font
  f = createFont("Candara-Bold-12.vlw", 12, true);

// using similar designations as to that from the 'Game of Life'
// I hope to use a similar grid to help sort out the words and lines of the poem
// as a starting point
  columns = width;
  rows = height;
  wide = width;
  high = height;
 
  String lines[] = loadStrings("come.txt");
  println("there are " + lines.length + " lines");
// use 'e' for 'elegy' for the integer variable in the for loop
  for (int e = 0; e < lines.length; e++)
  {
    String[] words = split(lines[e], ' ');
        for(int i = 0; i < words.length; i++)
          {
            for(int j = 0; j < words[i].length(); j++)
              {
                let = words[i].charAt(j);
                println(let);
              }
          }
         

    
      println(words);
      println(lines[e]);
      println(lines[e].length());
      println(let);

  }
// creates the background color of very light blue 
background(219, 243, 241);

}


// begin the function draw()
   
void draw() {
//for (int spacing = 0; spacing < 960; spacing = spacing + 10) { 
// assign the textFont 'f'
  textFont(f);
  fill(0);
  textAlign(CENTER);
  text((words), 45, 50);
  text(("words"), 90, 150);

    {

// call the function that creates a grid on the stage of the Sketch 
    drawGrid(wide, high);

    }
   
}


///////////////////////////////////////////////////////////////////////
// divides the functions from the main program areas
///////////////////////////////////////////////////////////////////////
   
// function 'drawGrid' simply draws a light colored grid on the 'stage'
void drawGrid(int wide, int high)
  {
// set a background of lines
  for (int x = 0; x < wide; x += 10)
  {
    for (int y = 0; y < high; y += 10)
    {
// sets the stroke color
      stroke(50, 50, 50);
// sets the strokeWeight
      strokeWeight(1);
// draws the vertical lines
      line(x, y, x, high);
// sets the stroke color to light gray
      stroke(30, 30, 30);
// sets the strokeWeight
      strokeWeight(1);
// draws the horizontal lines
      line(x, y, wide, y);
    }
  }
}
I still see a number of problems. Have you read the article I pointed to? Among other things, it shows you should not hide a global declaration with a local variable. You have a words global variable, and inside the loop, you declare a new variable of same name.

Other problem:
// create the string variable
  char words;
char doesn't declare a string, it declares a single character!

Other issue:
f = createFont("Candara-Bold-12.vlw", 12, true);
You probably want to use loadFont() there. When using createFont(), we specify a system font name, like "Arial" or "Times New Roman", not a .vlw font.

Thank you, PhiLho, I did read the articles you've posted, several times, as well as the reference article on Strings, and thought I had done things correctly.

I'm just slow. And I have a hard time learning from reading alone, I do better with someone teaching me, one small step at a time, which I realize is not at all the job of the forum, but all the same, you have shown remarkable patience and kindness. I'll see if I can add what you've just written to what I had before and see where I get.

Thanks,
Scotrick
I have no problem with the questions, I was just checking, as this "local variable hiding a global variable" problem has been explained (perhaps poorly) in the article. Now, Java can be subtle, eg. you can have legitimately several entities with same name that co-exists, and knowing what happens exactly can be hard...

So, in general, it is better to avoid declaring variables of identical names (but I know that differencing declaring vs. using is also commonly mixed up by beginners).

Now, I feel I have lost the original goal in details (like how to get each char of a word).
Why do you want to " convert each word into a number" again? What do you want to do with the numbers?
Thanks, PhiLho -

To answer your last question first:

My goal is eventually take two of the elegy by John Donne, Elegy 8,  and compare them, because though they are the same poem, they were copied by different scribes, and so each has slight differences in wording here and there throughout the copies.

I wanted to create a program that could load the poems, and then visually display the differences (and also, by default, the similarities) in some mildly artful way.

There are 48 copies of the same poem, and so I was hoping to build a framework that would be flexible enough so that eventually I could keep working on the program, refining it, so that an end user could choose which of the 48 to compare (or perhaps compare all at once, again, with some visual indicator of major differences).

As this is part of a larger study being done by a friend, the Donne poems are already supplied in a textual format, that with a little bit of effort, can be loaded straight into Processing.

My programming outline went something like this:

Load the text.
Create and assign each poem to an array.
Create and assign each word in the poem to an array.
Create and assign each letter in the poem to an array.
Convert each word into a number using ASCII (because it's a standard, rather than creating some numerical system of my own)
Convert an array to store not only the ASCII value of the word but where it occurs in the poem (in the case of duplicated ASCII numbers).

Then, using these numbers, create a variety of simple visualizations. Maybe print the poem to the stage (what I was working on at this point), and then having each successive iteration of the poem change the alpha of the words that are the same, only leaving fully visible the words that are different.

And so on. I figured once I had the words converted to numbers and in an array, I would really worry about the visualization part later, because I have more experience making fun simple cellular automata, like the bog standard Game Of Life, but it helped me learn how to create some nice color changes based on 2 or 3 value array data (I avoid the use of 2D and 3D because I don't yet know how to work with 3D).

In order to accomplish this set of goals, which seems very large to me, I wanted to get to where I could simply gather one word from a text file and display it to the screen. And so far, as you've noticed, I'm not doing very well.

I understand what you mean, I believe.

In the central loop, the variable 'words' is used in "String[] words = split(lines[e], ' ');
That's where you mean that I reused the variable 'words', right?

So, I need a new variable to store my data from the loaded text, which in this case is a string, and again, in this case, the word, 'come'.

When I tried creating, say, a new variable named elegyWord;
as a global variable:
char elegyWord;

But then, in your reply you wrote that 'char' can only declare a variable that can store a single character, am I understand you correctly? At any rate, when I tried to then assign my 'words' variable to the new variable 'elegyWord', I got the perhaps expected error, ' cannot convert from string to char' which makes sense, given what you've told me.

So, does that mean I should declare a new global array to hold the information from the words array?
And if so, how do I assign the new array to the words array? I'm going to give it a go, and if I fail, I'll be back. One day, I hope to be back with some pretty and interesting to share with you, rather than simply my beginner's mistakes.

If you want to see a fun program I wrote in ActionScript a long long time ago now, please visit:
http://www.scotrick.com/03_flash/01_aMazeOffBounce.html
This one lets you move white lines found on the right hand side of the screen, lay them on the 'play area, and then create a miniature musical composition as a moving line 'bounces' off the line. For an interesting screw up in the way I programmed the hit detection, you can place one line on top of another, creating a 'chord'.
or simply www.scotrick.com and the choose the 'flash' section to see others.

***

But in the meantime, I dream of getting this one word out of this .txt file and onto the screen.
Thanks again for your patience in dealing with such a beginner at Processing.
Scotrick

OK. Maybe I should ask this question, as the 'words' variable already is correctly storing the word I need, how do I display it on the Sketch's stage?

For example, I tried:
text((words), 45, 50);

Which to my understanding should have displayed whatever information the variable was holding at that time on the screen, 45 x, 50 y.

Is that not right? If not, is there a better way of getting this information onto the screen?

For anyone joining the conversation late, please note the code a few posts above, and also please excuse me, I tend to write too many words in my attempt to describe the problems.

Thanks,
Scotrick
I just posted up something that reads text into a tree.
The overlapping nodes in two different trees are the parts of the poems that are the same.
You can mouse over a node and it shows what part that node represents in the poem(s).
http://www.youtube.com/watch?v=sk0dSQ6snnw
But it is hard and is really separating on a two letter basis so that may not be what you need.
If any of the solutions above will work it is better to go with one of them.

Here is a basic program to make up a number for each word.
It needs a better parser and probably provides good reasons,
such as having to worry about chars between words,
to go with a method mentioned above.

void setup()
{
    byte[] b;
    int secretnumber=0;
  //  int secretvalues= {2,4,7,22,12};
    b= loadBytes("sentence.txt");
   
    for (int i=0; i<b.length; i++)
    {
      if (b[i]==32) {println(" - "+secretnumber); secretnumber=0; continue;}
      if (b[i]==13) {println(" - "+secretnumber); secretnumber=0; continue;}
      if (b[i]==10) {println(" - "+secretnumber); secretnumber=0; continue;}
      // or check for range of alphanumeric chars
     
      secretnumber+=b[i];
    print( (char)b[i] );
    }
   
}





I took a quick look at your Code

you have to restore your line to load a text file (line 43+16) and remove my replacement (17 and on) - I marked it bold.

I parsed the whole text now into an array "target" which has 2 dimensions: 1st for the lines (= different poems), 2nd for the single letters of this line.

Hope that gets your working.

Greetings, Chrisir   


Copy code
  1. // Scotrick - with help from programmers on the Processing forum, PhiLho and Kobby,
  2. // as well as help from the book, 'learning processing' example 18-6, parsing King Lear.
  3. //
  4. // This hopefully will be a program to parse from a .txt file a word and assign each letter an ASCII value
  5. // then combine those values to get a numerical value for the entire word,
  6. // ideally, not just the ASCII value of the word, but its position in the order of words.
  7. //
  8. // If this step is accomplished, then more words will be added to the array,
  9. // and hopefully compared.
  10. // create integer variables to store the stage width and height in columns and rows
  11. int columns, rows;
  12. // create integer variables to store the width and height of the stage
  13. int wide, high;
  14. // create the string variable
  15. String[] words;
  16. //String[] lines;
  17. String[] lines= {
  18.   "Come, Madam, come",
  19.   "Come, Madame, come",
  20.   "Come, Madam, she came",
  21.   "Come, Madam, she came.",
  22. }
  23. ;
  24. String [][] target ;
  25. // create the string variable
  26. char let;
  27. // the 'Pfont' variable to hold the standard font variable 'f'
  28. PFont f;
  29. // begin the function setup()
  30. void setup() {
  31.   // to create a grid for the letters of the complete poem, with each square being 10 pixels by 10 pixels
  32.   size(960, 840);
  33.   // load the font
  34.   // f = createFont("Candara-Bold-12.vlw", 12, true);
  35.   f = createFont("Arial", 14);
  36.   // using similar designations as to that from the 'Game of Life'
  37.   // I hope to use a similar grid to help sort out the words and lines of the poem
  38.   // as a starting point
  39.   columns = width;
  40.   rows = height;
  41.   wide = width;
  42.   high = height;
  43.   // String lines[] = loadStrings("come.txt");
  44.   println("there are " + lines.length + " lines");
  45.   words = split(lines[0], ' ');
  46.   target=new String [lines.length ] [lines[0].length()+79] ;
  47.   int letter_index=0;
  48.   // use 'e' for 'elegy' for the integer variable in the for loop
  49.   for (int e = 0; e < lines.length; e++)
  50.   {
  51.     words = split(lines[e], ' ');
  52.     for (int i = 0; i < words.length; i++)
  53.     {
  54.       for (int j = 0; j < words[i].length(); j++)
  55.       {
  56.         let = words[i].charAt(j);
  57.         print(let);
  58.         //target[e][j]=new String();
  59.         StringBuilder fred = new StringBuilder(let);
  60.         fred.append(let);
  61.         target[e][letter_index]=fred.toString();
  62.         println("    "  + target[e][letter_index]);
  63.         letter_index++;
  64.       }
  65.     }
  66.     println(words);
  67.     println(lines[e]);
  68.     println(lines[e].length());
  69.     println(let);
  70.     letter_index=0;
  71.   }
  72.   // creates the background color of very light blue
  73.   background(219, 243, 241);
  74.   println("end of setup().");
  75. }
  76. // begin the function draw()
  77. void draw() {
  78.   //for (int spacing = 0; spacing < 960; spacing = spacing + 10) {
  79.   // assign the textFont 'f'
  80.   textFont(f);
  81.   fill(0);
  82.   textAlign(CENTER);
  83.   //text(words[0], 45, 50);
  84.   //text("words", 90, 150);
  85.   // call the function that creates a grid on the stage of the Sketch
  86.   // drawGrid(wide, high);
  87.   fill (255);
  88.   textSize(32);
  89.   for (int e = 0; e < lines.length; e++)
  90.   { 
  91.     // text(lines[e], 345, 40*e+120);
  92.   }
  93.   // -------------------------------------------------
  94.   textSize(22);
  95.   for (int e = 0; e < lines.length; e++) {
  96.     //println(target[e].length);
  97.     //println(target[e]);
  98.     //println(target[e][0]);   
  99.     textSize(12);
  100.     text(e, 0*27+12, e*30+ 100);
  101.     for (int j = 0; j < target[e].length; j++) {
  102.       // join
  103.       if (target[e][j]!=null) {
  104.         textSize(12);
  105.         text(j, j*17+42, 70);       
  106.         textSize(22);
  107.         text(target[e][j], j*17+42, e*30+ 100);
  108.         print(target[e][j]+" ");
  109.       }
  110.     }
  111.     println();
  112.   }
  113. }
  114. ///////////////////////////////////////////////////////////////////////
  115. // divides the functions from the main program areas
  116. ///////////////////////////////////////////////////////////////////////
  117. // function 'drawGrid' simply draws a light colored grid on the 'stage'
  118. void drawGrid(int wide, int high)
  119. {
  120.   // set a background of lines
  121.   for (int x = 0; x < wide; x += 10)
  122.   {
  123.     for (int y = 0; y < high; y += 10)
  124.     {
  125.       // sets the stroke color
  126.       stroke(50, 50, 50);
  127.       // sets the strokeWeight
  128.       strokeWeight(1);
  129.       // draws the vertical lines
  130.       line(x, y, x, high);
  131.       // sets the stroke color to light gray
  132.       stroke(30, 30, 30);
  133.       // sets the strokeWeight
  134.       strokeWeight(1);
  135.       // draws the horizontal lines
  136.       line(x, y, wide, y);
  137.     }
  138.   }
  139. }

Seems I'm not the only person who assigns funny names to variables. You called your StringBuilder "fred". i call my BlobDetection objects "bob"! :)
Chrisir -

Thank you for your additions to the code that we (book, forum and I :) ) had written, but I can't figure out what I need to delete and what I need to keep in order to get a running version of your code. In particular, lines 88-112, some of which are bold, and some of which aren't, as well as where in the setup I need to stop deleting bold code.

I'll use your reference 'target' array and go back through and see if I can suss it out. However, if you happen to see this note and felt like helping me by making what I should be deleting and what I should be keeping, a little clearer, that would really help.

Cheers for the time and energy, and you're right, if I understand your reasoning, this would be a good start for my project.

Thank you,
Scotrick


the Code above runs as it is with array

here I made a version that should load your file (file name is in line 36 now)

Copy code
  1. // Scotrick - with help from programmers on the Processing forum, PhiLho and Kobby,
  2. // as well as help from the book, 'learning processing' example 18-6, parsing King Lear.
  3. //
  4. // This hopefully will be a program to parse from a .txt file a word and assign each letter an ASCII value
  5. // then combine those values to get a numerical value for the entire word,
  6. // ideally, not just the ASCII value of the word, but its position in the order of words.
  7. //
  8. // If this step is accomplished, then more words will be added to the array,
  9. // and hopefully compared.
  10. // create integer variables to store the stage width and height in columns and rows
  11. int columns, rows;
  12. // create integer variables to store the width and height of the stage
  13. int wide, high;
  14. // create the string variable
  15. String[] words;
  16. String[] lines;
  17. String [][] target ;
  18. // create the string variable
  19. char let;
  20. // the 'Pfont' variable to hold the standard font variable 'f'
  21. PFont f;
  22. // begin the function setup()
  23. void setup() {
  24.   // to create a grid for the letters of the complete poem, with each square being 10 pixels by 10 pixels
  25.   size(960, 840);
  26.   // load the font
  27.   // f = createFont("Candara-Bold-12.vlw", 12, true);
  28.   f = createFont("Arial", 14);
  29.   // using similar designations as to that from the 'Game of Life'
  30.   // I hope to use a similar grid to help sort out the words and lines of the poem
  31.   // as a starting point
  32.   columns = width;
  33.   rows = height;
  34.   wide = width;
  35.   high = height;
  36.   String lines[] = loadStrings("come.txt");
  37.   println("there are " + lines.length + " lines");
  38.   words = split(lines[0], ' ');
  39.   target=new String [lines.length ] [lines[0].length()+79] ;
  40.   int letter_index=0;
  41.   // use 'e' for 'elegy' for the integer variable in the for loop
  42.   for (int e = 0; e < lines.length; e++)
  43.   {
  44.     words = split(lines[e], ' ');
  45.     for (int i = 0; i < words.length; i++)
  46.     {
  47.       for (int j = 0; j < words[i].length(); j++)
  48.       {
  49.         let = words[i].charAt(j);
  50.         print(let);
  51.         //target[e][j]=new String();
  52.         StringBuilder fred = new StringBuilder(let);
  53.         fred.append(let);
  54.         target[e][letter_index]=fred.toString();
  55.         println("    "  + target[e][letter_index]);
  56.         letter_index++;
  57.       }
  58.     }
  59.     println(words);
  60.     println(lines[e]);
  61.     println(lines[e].length());
  62.     println(let);
  63.     letter_index=0;
  64.   }
  65.   // creates the background color of very light blue
  66.   background(219, 243, 241);
  67.   println("end of setup().");
  68. }
  69. // begin the function draw()
  70. void draw() {
  71.   //for (int spacing = 0; spacing < 960; spacing = spacing + 10) {
  72.   // assign the textFont 'f'
  73.   textFont(f);
  74.   fill(0);
  75.   textAlign(CENTER);
  76.   //text(words[0], 45, 50);
  77.   //text("words", 90, 150);
  78.   // call the function that creates a grid on the stage of the Sketch
  79.   // drawGrid(wide, high);
  80.   fill (255);
  81.   textSize(32);
  82.   for (int e = 0; e < lines.length; e++)
  83.   {
  84.     // text(lines[e], 345, 40*e+120);
  85.   }
  86.   // -------------------------------------------------
  87.   textSize(22);
  88.   for (int e = 0; e < lines.length; e++) {
  89.     //println(target[e].length);
  90.     //println(target[e]);
  91.     //println(target[e][0]);  
  92.     textSize(12);
  93.     text(e, 0*27+12, e*30+ 100);
  94.     for (int j = 0; j < target[e].length; j++) {
  95.       // join
  96.       if (target[e][j]!=null) {
  97.         textSize(12);
  98.         text(j, j*17+42, 70);      
  99.         textSize(22);
  100.         text(target[e][j], j*17+42, e*30+ 100);
  101.         print(target[e][j]+" ");
  102.       }
  103.     }
  104.     println();
  105.   }
  106. }
  107. ///////////////////////////////////////////////////////////////////////
  108. // divides the functions from the main program areas
  109. ///////////////////////////////////////////////////////////////////////
  110. // function 'drawGrid' simply draws a light colored grid on the 'stage'
  111. void drawGrid(int wide, int high)
  112. {
  113.   // set a background of lines
  114.   for (int x = 0; x < wide; x += 10)
  115.   {
  116.     for (int y = 0; y < high; y += 10)
  117.     {
  118.       // sets the stroke color
  119.       stroke(50, 50, 50);
  120.       // sets the strokeWeight
  121.       strokeWeight(1);
  122.       // draws the vertical lines
  123.       line(x, y, x, high);
  124.       // sets the stroke color to light gray
  125.       stroke(30, 30, 30);
  126.       // sets the strokeWeight
  127.       strokeWeight(1);
  128.       // draws the horizontal lines
  129.       line(x, y, wide, y);
  130.     }
  131.   }
  132. }


Chrisir's, I'm sorry, I still couldn't get your version to run. Now, I'm even more confused, comparing the latter one your posted with the first. I think the problem is that I'm still such a beginner that even knowing which of your lines you intend for me to keep as comments and which you expect me to uncomment so that they will run is beyond me. Please take a look at the program I posted below to get a better idea of the level where I'm working, and if you have time, I'd love to talk with you further about your array system, because it does look like it would be a great place to work from.
Thank you for your time. And as the other poster mentioned, I too like your variable names, if this weren't code I wanted to share with other academics, it would be much more quirky in naming convention. I too want to stress, however, that this isn't an 'assignment', this is more for the academic fun of 16th and 17th poetry. :)
Well, that and making pretty pictures of data.
Hi, all. I wanted to let you know that with your help, I was able to show my dissertation director some progress towards our goal, that of the analysis of the John Donne poems. I'll be posting the program I finished with your help, though it doesn't do much yet.

By that I mean that it can parse the Donne poem and displays the words randomly on the page. I can't find the Flash drive that I stored my final on, but as soon as I do, I'll post it here. I can't say enough kind things about you all. Also, I wanted to mention the book, Form & Code, as another resource for anyone working along these lines, as that book compares two texts by counting the number and occurrences of words of two texts, Frankenstein and Dracula.

Another text that I've found useful is, Interactivity, that added a very simple line of code to make sure that if the array being used hits a 'null' it won't thrown an error, instead you can then program what it should do. This line I haven't seen in any other loop that cycles through an array.

Thanks again, and I'll be back in touch soon with my own rather simplistic draft of the various programs we've all been creating in this thread. :)

Note that I've tried to credit the help that I had received at the time I presented this program. Please let me know if anyone would prefer a different name or way of being credited, or if you see something else within this program that you feel I haven't credited properly. It is very important for me to make sure everyone gets as much recognition for this as possible, as while not exactly Earth shattering, :) , the program I hope to make will hopefully be of some importance to the Donne scholars, and I want to be sure that if I manage to finish my dissertation everyone is given proper due.

Right now, I'm on medical leave due to brain damage, but I hope to be back at school next semester. I admit that might not happen, but whether or not I'm able to return to the PhD program, I will continue working on this problem. Since I started this thread, I've learned that I was wrong in that the Elegy I'm studying, known by its first few words, Come, Madam, Come, or its title, "To His Mistress Going To Bed" has 68 surviving manuscript copies, and it is those copies that I'm going to be using to create various data visualizations from.

The following program simply is the very first step, where I managed to pull the words from the text file and display them on screen. For now, it simply counts the number of times each words appears in the poem, and then puts the numbers and the words on the screen in random positions and colors. Below the code, I'm including the .txt file so that you can see poem in its entirety.

// Patrick Scott Vickers - with help from programmers on the Processing forum, PhiLho and Kobby
//
// This is a program to pull words from a text file, an Elegy by John Donne
// then combine those values to get a numberical value for the entire word,
// ideally, not just the ASCII value of the word, but its position in the order of words.
//
// If this step is accomplished, then more words will be added to the array,
// and hopefully compared.

// create integer variables to store the stage width and height in columns and rows
  int columns, rows;

// create integer variables to store the width and height of the stage
  int wide, high;
// create integer variables to store the x width and y height of the stage
  int x, y;
 
// create an integer to hold the length of a word
  int wordLength;

// a variable to hold onto a font
  PFont f;
// the array to hold all of the text
  String[] eachPoem;
// where are we in the text
  int counter = 386;  
// delimiters
  String delimiters = " ,.?!;:[]\r\n\f";

void setup() {
    size(960, 840);
   
// using names from the 'Game of Life'
// I hope to use a similar grid to sort out the words and lines of the poem(s)
// as a helpful method of seeing the words
    columns = width;
    rows = height;
    wide = width;
    high = height;
 
// load the font
    f = loadFont( "BookmanOldStyle-Bold-96.vlw" );
 
// load an array of strings

    String rawtext [] = loadStrings("AB_come_madam.txt");
 
// join the big array together as one long string
    String everything = join(rawtext, "" );
 
// and then split into that set into an array of individual words
// with the the following delimiters 
    eachPoem = splitTokens(everything,delimiters);
    frameRate(3);
    background(255);
}

void draw() {
  fill(19-(random(counter)), 28-(random(counter)), 255-(random(counter)), 001);
  rect(0,0, 960, 840);

 
// one word at a time from the poem
  String theword = eachPoem[counter];
  println(theword);
  wordLength = theword.length();
// count how many times that word appears in the poem
  int total = 0;
  for (int i = 0; i < eachPoem.length; i ++ ) {
    if (theword.equals(eachPoem[i])) {
      total ++;
    }
  }
 
// display the text and total times the word appears
// use random numbers to vary the placement and color
// of the words from the poem
  textFont(f);
// change the color of the number that shows how often a word appears
  fill(200-((random(20))*wordLength), 30*(random(00)), 12, 3*(random(10)));
  text(theword,1+((random(960))+wordLength*10),90*wordLength);
  println(wordLength);
// change the color of the word as it appears on the Sketch's stage
  fill(0+(random(wordLength)), 26, 255, 10);
// change the location of each word, based on the size of the stage
  text(total,1+(random(960)),1+(random(840)));
 
// move onto the next word
  counter = (counter + 1) % eachPoem.length;
 

}

// function 'drawGrid' simply draws a light colored grid on the 'stage'
void drawGrid(int wide, int high) {
// set a background of lines
  for (int x = 0; x < wide; x += 12) {
    for (int y = 0; y < high; y += 12) {
// sets the stroke color to light gray
      stroke(30, 30, 30);
// sets the strokeWeight
      strokeWeight(1);
// draws the vertical lines
      line(x, y, x, high);
// draws the horizontal lines
      line(x, y, wide, y);
    }
  }
}

Here's the poem that is inside my 'data' folder

Elegy XIX: To His Mistress Going to Bed


001 Come, Madam, come, all rest my powers defy,

002 Until I labour, I in labour lie.

003 The foe oft-times, having the foe in sight,

004 Is tired with standing, though they never fight.

005 Off with that girdle, like heaven's zone glistering‚

006 But a far fairer world encompassing.

007 Unpin that spangled breast-plate, which you wear‚

008 That th'eyes of busy fools may be stopped there:

009 Unlace yourself, for that harmonious chime

010 Tells me from you that now 'tis your bed time.

011 Off with that happy busk, whom I envy

012 That still can be, and still can stand so nigh.

013 Your gown's going off such beauteous state reveals

014 As when from flowery meads th'hills shadow steals.

015 Off with your wiry coronet and show

016 The hairy diadem which on you doth grow.

017 Off with those shoes: and then safely tread

018 In this love's hallowed temple, this soft bed.

019 In such white robes heaven's angels used to be

020 Received by men; thou Angel bring'st with thee

021 A heaven like Mahomet's Paradise; and though

022 Ill spirits walk in white, we easily know

023 By this these Angels from an evil sprite:

024 They set out hairs, but these the flesh upright.

025 License my roving hands, and let them go

026 Behind before, above, between, below.

027 Oh my America, my new found land,

028 My kingdom, safeliest when with one man manned,

029 My mine of precious stones, my Empery,

030 How blessed am I in this discovering thee.

031 To enter in these bonds is to be free,

032 Then where my hand is set my seal shall be.

033 Full nakedness, all joys are due to thee.

034 As souls unbodied, bodies unclothed must be

035 To taste whole joys. Gems which you women use

036 Are as Atlanta's balls, cast in men's views,

037 That when a fool's eye lighteth on a gem

038 His earthly soul may covet theirs not them.

039 Like pictures, or like books' gay coverings made

040 For laymen, are all women thus arrayed;

041 Themselves are mystic books, which only we

042 Whom their imputed grace will dignify

043 Must see revealed. Then since I may know,

044 As liberally as to a midwife show

045 Thyself; cast all, yea this white linen hence.

046 Here is no penance, much less innocence.

047 To teach thee, I am naked first: why then

048 What need'st thou have more covering than a man.