Loading...
Logo
Processing Forum

using saveStrings();

in Programming Questions  •  1 year ago  
I wrote program and I need to save the output in text file
I found this function when i used there are error can someone explain this function how it work


Word w = (Word) words.get(s);
    w.count(); 

 if (w.count >4)
after this step i want to save it in text file 

Replies(154)

What is Word?
Among other things...
this is all the code 
HashMap words;  // HashMap object

String[] tokens;  // Array of all words from input file
int counter;

PFont f;

void setup() {
  size(640, 360);
  words = new HashMap();

  // Load file and chop it up
  String[] lines = loadStrings("dracula.txt");
  String allText = join(lines, " ");
  tokens = splitTokens(allText, " ,.?!:;[]-");
  f = createFont("Georgia", 36, true);  
}

void draw() {
  background(255);
  fill(0);
  
  // Look at words one at a time
  String s = tokens[counter];
  counter = (counter + 1) % tokens.length;

  // Is the word in the HashMap
  if (words.containsKey(s)) {
    // Get the word object and increase the count
    // We access objects from a HashMap via its key, the String
    Word w = (Word) words.get(s);
    w.count(); 
  } else {
    // Otherwise make a new word
    Word w = new Word(s);
    // And add to the HashMap
    // put() takes two arguments, "key" and "value"
    // The key for us is the String and the value is the Word object
    words.put(s, w);    
  }

  // Make an iterator to look at all the things in the HashMap
  Iterator i = words.values().iterator();

  // x and y will be used to locate each word
  float x = 0;
  float y = height-10;

  while (i.hasNext()) {
    // Look at each word
    Word w = (Word) i.next();
    
    // Only display words that appear 3 times
    if (w.count > 3) {
      // The size is the count
      int fsize = constrain(w.count, 0, 100);
      textFont(f, fsize);
      text(w.word, x, y);
      // Move along the x-axis
      x += textWidth(w.word + " ");
    }
    
    // If x gets to the end, move Y
    if (x > width) {
      x = 0;
      y -= 100;
      // If y gets to the end, we're done
      if (y < 0) {
        break; 
      }
    }
  } 
}

I want the output save it in text file
Still... what is Word?
If you can get the text from the word, then convert it to a String[] and pass it to the function.
word is class
class Word {
  
  int count;
  String word;
  
  Word(String s) {
    word = s;
    count = 1;
  }
  
  void count() {
    count++;
  }

}  
I am not sure to understand what exactly you want to save.
But you have to create an array of strings, of the right size, and fill it with the data to save.
Then you call saveStrings().
What I want    
if (w.count > 3) 
If the word repeated more than 3 times 
 I need to save it in another text file.
Put all the words with frequency above 3 in an array list.
Convert the array list to an array:
String[] frequentWords = frequentWordList.toArray(new String[frequentWordList.size()]);
Then use saveStrings(fileName, frequentWords);
I don't know how to use it  can you give me example how i can  Convert the array list to an array
My third line precisely shows how to do it...

At least, it inspired me to add the information in the Why use ArrayList instead of array with append()? article.
Copy code
  1. String[] commonWords = {"Dog","Cat","Box","Mouse"}; // Here is a list of Strings.
  2. commonWords = append( commonWords, "Cheese" ); // Here I add a new item to the list.
  3. saveStrings( "output.txt", commonWords ); // Here I save the list.
Thanks so much it is work
but I have another problem only one word in the output file 
I need all the word can you explain where my problem is 

String words = w.word;
String[] list = split(words, ' ');

saveStrings("result.txt", list);

Most likely, the text that each Word stores only contains on space-separated word.
Try printing out what the words actually contain like so:

Copy code
  1. for(int i = 0; i < words.size(); i ++) println(words.get(i).word);

See for yourself... I can't test it because I don't have "dracula.txt".
I test it I have message error 
The function size does't exist 


this is text can save it in text file as  "dracula.txt".


"What does this tell us?  Not much?  No!  The Count's child thought
see nothing, therefore he speak so free.  Your man thought see
nothing.  My man thought see nothing, till just now.  No!  But there
comes another word from some one who speak without thought because
she, too, know not what it mean, what it might mean.  Just as there
are elements which rest, yet when in nature's course they move on
their way and they touch, the pouf!  And there comes a flash of light,
heaven wide, that blind and kill and destroy some.  But that show up
all earth below for leagues and leagues.  Is it not so?  Well, I shall
explain.  To begin, have you ever study the philosophy of crime?
'Yes' and 'No.'  You, John, yes, for it is a study of insanity.  You,
no, Madam Mina, for crime touch you not, not but once.  Still, your
mind works true, and argues not a particulari ad universale.  There is
this peculiarity in criminals.  It is so constant, in all countries
and at all times, that even police, who know not much from philosophy,
come to know it empirically, that it is.  That is to be empiric.  The
criminal always work at one crime, that is the true criminal who seems
predestinate to crime, and who will of none other.  This criminal has
not full man brain.  He is clever and cunning and resourceful, but he
be not of man stature as to brain.  He be of child brain in much.  Now
this criminal of ours is predestinate to crime also.  He, too, have
child brain, and it is of the child to do what he have done.  The
little bird, the little fish, the little animal learn not by
principle, but empirically.  And when he learn to do, then there is to
him the ground to start from to do more.  'Dos pou sto,' said
Archimedes.  'Give me a fulcrum, and I shall move the world!'  To do
once, is the fulcrum whereby child brain become man brain.  And until
he have the purpose to do more, he continue to do the same again every
time, just as he have done before!  Oh, my dear, I see that your eyes
are opened, and that to you the lightning flash show all the leagues,"
for Mrs. Harker began to clap her hands and her eyes sparkled.

Okay, I must be confusing myself now...
I'm getting words.size() to work fine, but... why is the value received from words.get(i) not a Word?

There's something weird with your code that I'm not picking up on.

Also, go to Edit > Auto Format to clean up your code...
This is word class
class Word {
  
  int count;
  String word;
  
  Word(String s) {
    word = s;
    count = 1;
  }
  
  void count() {
    count++;
  }

}  

Thanks so much for your response because I really need help

I will explain to you
if (words.containsKey(s)) {
    // Get the word object and increase the count
    // We access objects from a HashMap via its key, the String
    Word w = (Word) words.get(s);
    w.count(); 
  } else {
    // Otherwise make a new word
    Word w = new Word(s);
    // And add to the HashMap
    // put() takes two arguments, "key" and "value"
    // The key for us is the String and the value is the Word object
    words.put(s, w);    
  }

  // Make an iterator to look at all the things in the HashMap
  Iterator i = words.values().iterator();

  // x and y will be used to locate each word
  float x = 0;
  float y = height-10;

  while (i.hasNext()) {
    // Look at each word
    Word w = (Word) i.next();
    
    // Only display words that appear 3 times
    if (w.count > 3) {


////from this part the repeated word displayed on the screen by the x and y 
at this step I need to save it in text file not in the screen 
      // The size is the count
      int fsize = constrain(w.count, 0, 100);
      textFont(f, fsize);
      text(w.word, x, y);
      // Move along the x-axis
      x += textWidth(w.word + " ");
    }
    
    // If x gets to the end, move Y
    if (x > width) {
      x = 0;
      y -= 100;
      // If y gets to the end, we're done
      if (y < 0) {
        break; 
      }
I hope you understand me
So... you want to combine all of the words that have a count greater than three... and print it to a text file?
You need to put all of the words into another list, and then print that list...

Like so:

Copy code
  1. //In the beginning of draw()
  2. String[] outputText = new String[0]; //Create the text array to write to a file

  3. //Inside "if (w.count > 3) {"
  4. outputText = append(outputText, w.word);

  5. //At the end of draw()
  6. saveStrings("filename", outputText);

That should work...
Thanks so so much
it is works good

I have another step
I will do it by myself first and then if I need help I will ask you

Now I need to ignore all the common words in the file
like the, on, in, 
Create a list of the common words that you want to exclude; then, go through and remove any of those words from the list.
This is what I understood but I have error 

 String[] ignore = { "a", "of", "the", "i", "it", "you", "and", "to","in","on","that" };

boolean ignoreWord(String what)
{
  for (int i = 0; i < ignore.length; i++) {
    if (what.equals(ignore[i])) {
      return true;
    }
  }
  return false;
}

" I have error"
It might be interesting to report what error you have...
the error message  unexpected token:Boolean

boolean ignoreWord(String what)
I don;t know why???
Hard to tell without context, but remember that you cannot put a function inside another function.
you right I have to put it outside the function 
Now I have no error but still the common word appear 

Where the problem please
Do you actually call the function to remove the words?
That would be done, presumably, after loading the words from the file...
I did n't because I have problem how to call the function 
This is the loading file
 String[] lines = loadStrings("soso.txt");
  String allText = join(lines, " ");
  tokens = splitTokens(allText, " ,.?!:;[]-");
    where should call the function


String[] ignore = { "a", "of", "the", "i", "it", "you", "and", "to","in","on","that" };

boolean ignoreWord(String what)
{
  for (int i = 0; i < ignore.length; i++) {
    if (what.equals(ignore[i])) {
      return true;
    }
  }
  return false;
}

The function won't do anything unless you use it...
Basically, you have to loop through the words and test each word; if the function come back true, delete the word; if it comes back false, keep the word. For example:

Copy code
  1. for(int i = 0; i < tokens.length; i ++) {
  2.   if(ignoreWord(tokens[i])) {
  3.     println(i);
  4.    
  5.     String[] before = subset(tokens, 0, i);
  6.     String[] after = subset(tokens, min(i + 1, tokens.length), tokens.length - 1 - i);
  7.    
  8.     tokens = concat(before, after);
  9.     i --;
  10.   }
  11. }

Notes:

Also, in your ignore check function, you can convert the text to lower case for a better comparison:

Copy code
  1. if (what.toLowerCase().equals(ignore[i])) {
WOW!!!!!!!!!!!!!!!
Thanks so much it works very good.

Now I have the last step visualization the output data by drawing graph 
nodes and edges
nodes represents the frequent word and edges represent the relationship
Did you have any idea to share i will start by myself and then I will ask if I have ?
I think to represent nodes not difficult but to fine relationship to draw the edges

What relationship between words are you trying to represent?
I don't now yet any relation but how to represent nodes without edges it must have relation to draw
At this point it's sort of hard to help you because we have no idea what your code currently looks like.
As your original question that you asked is now answered, I would start a new thread in the Programming Questions forum that has a descriptive title of your problem, and posts the current code and a description of what you want to add next.

Don't give us a partial description! We get that you now want nodes, and it seems that you'll want relations/edges next, so work out what you want the FINISHED thing to do, and ask for help getting to that (and not just doing it one step at a time).

Don't give us partial code! If we can't run it right away, we're unlikely to help. If you're missing a class definition, or are using fonts, files, or images we don't have, it's unlikly you'll get a good response.

I'm serious. If your original thread had been:

"Here is a text file: <text file>. I want to count the occurrence of each word, make a list of those words that appear three or more times, and then draw a graph that has those popular words on the nodes and edges between the nodes showing the relationship <some relationship>. Here is what I have so far: <current code>"

... Then someone could probably have banged out what you wanted in a good half hour.
I agree with most of the advices, except the " someone could probably have banged out what you wanted in a good half hour." which is true, but probably not so much helpful. At least fefetopf learned from each step (I hope!) while if we do the assignment for him (?), the learning value is low (even if it is fun to the person doing it...).
Thanks so much I will start when I faced problem I will ask for help
As I said I am new user for this software and I need to learn more and more and thanks so much to support me to learn a lot of things about progress because If I have problem and no one help me I will take long time to solve the problem but again thanks so much
I have this program,I need to write the word that read it inside the node and when I draw the edge if the word already found just draw the edge don't repeat the word 
this is the program 

int nodeCount;
Node[] nodes = new Node[100];
HashMap nodeTable = new HashMap();

int edgeCount;
Edge[] edges = new Edge[500];

static final color nodeColor   = #F0C070;
static final color selectColor = #FF3030;
static final color fixedColor  = #FF8080;
static final color edgeColor   = #000000;

PFont font;


void setup() {
  size(600, 600);  
  loadData();
  font = createFont("SansSerif", 10);
  writeData();  
}


void writeData() {
  PrintWriter writer = createWriter("filter.dot");
  writer.println("digraph output {");
  for (int i = 0; i < edgeCount; i++) {
    if( edges[i].from.label == edges[i].to.label)return;
    String from = "\"" + edges[i].from.label + "\"";
    String to = "\"" + edges[i].to.label + "\"";
    writer.println(TAB + from + " ==> " + to + ";");
  }
  writer.println("}");
  writer.flush();
  writer.close();
}


void loadData() {
  String[] lines = loadStrings("filter.txt");
  
  // Make the text into a single String object
  String line = join(lines, " ");
  
  // Replace -- with an actual em dash
  line = line.replaceAll("--", "\u2014");
  
  // Split into phrases using any of the provided tokens
  String[] phrases = splitTokens(line, ".,;:?!\u2014\"");
  //println(phrases);

  for (int i = 0; i < phrases.length; i++) {
    // Make this phrase lowercase
    String phrase = phrases[i].toLowerCase();
    // Split each phrase into individual words at one or more spaces
    String[] words = splitTokens(phrase, " ");
    for (int w = 0; w < words.length-1; w++) {
      addEdge(words[w], words[w+1]);
    }
  }
}


void addEdge(String fromLabel, String toLabel) {

  
  Node from = findNode(fromLabel);
  Node to = findNode(toLabel);
  from.increment();
  to.increment();
  
  for (int i = 0; i < edgeCount; i++) {
    if (edges[i].from == from && edges[i].to == to) {
      edges[i].increment();
      return;
    }
  } 
  
  Edge e = new Edge(from, to);
  e.increment();
  if (edgeCount == edges.length) {
    edges = (Edge[]) expand(edges);
  }
  edges[edgeCount++] = e;
}




Node findNode(String label) {
  label = label.toLowerCase();
  Node n = (Node) nodeTable.get(label);
  if (n == null) {
    return addNode(label);
  }
  return n;
}


Node addNode(String label) {
  Node n = new Node(label);  
  if (nodeCount == nodes.length) {
    nodes = (Node[]) expand(nodes);
  }
  nodeTable.put(label, n);
  nodes[nodeCount++] = n;  
  return n;
}


void draw() {
  if (record) {
    beginRecord(PDF, "resul.pdf");
  }

  background(255);
  textFont(font);  
  smooth();  
  
  for (int i = 0 ; i < edgeCount ; i++) {
    edges[i].relax();
  }
  for (int i = 0; i < nodeCount; i++) {
    nodes[i].relax();
  }
  for (int i = 0; i < nodeCount; i++) {
    nodes[i].update();
  }
  for (int i = 0 ; i < edgeCount ; i++) {
    edges[i].draw();
  }
  for (int i = 0 ; i < nodeCount ; i++) {
    nodes[i].draw();
  }
  
  if (record) {
    endRecord();
    record = false;
  }
}


boolean record;

void keyPressed() {
  if (key == 'r') {
    record = true;
  }
}


Node selection; 


void mousePressed() {
  // Ignore anything greater than this distance
  float closest = 20;
  for (int i = 0; i < nodeCount; i++) {
    Node n = nodes[i];
    float d = dist(mouseX, mouseY, n.x, n.y);
    if (d < closest) {
      selection = n;
      closest = d;
    }
  }
  if (selection != null) {
    if (mouseButton == LEFT) {
      selection.fixed = true;
    } else if (mouseButton == RIGHT) {
      selection.fixed = false;
    }
  }
}


void mouseDragged() {
  if (selection != null) {
    selection.x = mouseX;
    selection.y = mouseY;
  }
}


void mouseReleased() {
  selection = null;
}
this is the first class edges 
class Edge {
  Node from;
  Node to;
  float len;
  int count;


  Edge(Node from, Node to) {
    this.from = from;
    this.to = to;
    this.len = 50;
  }
  
  
  void increment() {
    count++;
  }
  
  
  void relax() {
    float vx = to.x - from.x;
    float vy = to.y - from.y;
    float d = mag(vx, vy);
    if (d > 0) {
      float f = (len - d) / (d * 3);
      float dx = f * vx;
      float dy = f * vy;
      to.dx += dx;
      to.dy += dy;
      from.dx -= dx;
      from.dy -= dy;
    }
  }


  void draw() {
    stroke(edgeColor);
    strokeWeight(0.35);
    line(from.x, from.y, to.x, to.y);
  }
}



this is the second class nodes
{
  float x, y;
  float dx, dy;
  boolean fixed;
  String label;
  int count;


  Node(String label) {
    this.label = label;
    x = random(width);
    y = random(height);
  }
  
  
  void increment() {
    count++;
  }
  
  
  void relax() {
    float ddx = 0;
    float ddy = 0;

    for (int j = 0; j < nodeCount; j++) {
      Node n = nodes[j];
      if (n != this) {
        float vx = x - n.x;
        float vy = y - n.y;
        float lensq = vx * vx + vy * vy;
        if (lensq == 0) {
          ddx += random(1);
          ddy += random(1);
        } else if (lensq < 100*100) {
          ddx += vx / lensq;
          ddy += vy / lensq;
        }
      }
    }
    float dlen = mag(ddx, ddy) / 2;
    if (dlen > 0) {
      dx += ddx / dlen;
      dy += ddy / dlen;
    }
  }


  void update() {
    if (!fixed) {      
      x += constrain(dx, -5, 5);
      y += constrain(dy, -5, 5);
      
      x = constrain(x, 0, width);
      y = constrain(y, 0, height);
    }
    dx /= 2;
    dy /= 2;
  }


  void draw() {
    fill(nodeColor);
    stroke(0);
    strokeWeight(20);
    //println(w);
    
    ellipse(x, y, count, count);
    float w = textWidth(label);
    fill(201);

    if (count > w+2) {
      fill(0);
      textAlign(CENTER, CENTER);
      text(label, x, y);
    }
  }
}


========
and this is my file

filter.txt(the name of the file)


table
array
addressing
keys
key
hash


Could you explain the problem further?

You need to display the text that each node contains... you have already done that, but the number of word occurrences needs to be higher, first...
this is the first problem the word doesn't appear inside the node.
the second problem the edge between words I need draw edge if the word inside the node not repeated 
if we already has the word inside the node draw the edge if not draw the edge and the node.
In your code, you only display the text if count > w + 2.
If I'm correct, count is the number of times that the words appears, and none of the words appear more than three times...
I found myself interested with processing. 
I have problem how I can read text file depended on the sentences that included in file 
I need frequent word from the text file in every sentence and it should give me the word and frequent and the number of sentence that included this frequent 

HashMap words;  // HashMap object

String[] sentences;  // Array of all sentences from input file
int counter;

PFont f;



void setup() 
{
  size(640, 360);
  words = new HashMap();

//loading the file 
  String[] lines = loadStrings("input.txt");
  String allText = join(lines, " ");
  sentences = splittokens(allText, " ,.?!:;[]-");

  for(int i = 0; i < sentences.length; i ++) {
     
    String[] before = subset(sentences, 0, i);
    String[] after = subset(sentences, min(i + 1, sentences.length), sentences.length - 1 - i);
   
    sentences = concat(before, after);
    i --;
  }
}
  
  f = createFont("Georgia", 36, true);  
}
I'm afraid I don't understand your problem... while I'm at it, I don't quite understand you in general.
Is this related to the original problem... or the various incarnations of it?
I really need to improve myself by discussion I understand when I discuss with others.
and i new with progress I still practicing I need more experience 
How I can write in the output file the frequent word and the count of it and the word in any sentence appear
for example
word    frequent   number of sentence 
milk       3             4,5,6(in sentence number 4 and 5 and 6)
Okay, I think I understand, now...
You want to generate a table containing all of the words, their frequencies, and their appearances.

You have a couple of options for formatting the data, using purely text-based format...
  • You could export it as a .tsv file (tab-separated values), or some other table format (I have no experience in this area, although I think it will work the best...
  • You can export a plain text file, doing the formatting yourself...

Either way, you'll have to get the data... I'll leave the output up to you.
I think you already have the data sorted, so I'll try to build off of that...

I would recommend creating a class to store all of the data for each word. If I'm correct, you're currently using Strings... This class would contain the name of the word, the number of times that it has occurred, and a list of sentences in which it has appeared.

Then, to output the data, merely create a function to return a formatted line of the data (basically, return a String with all of the values formatted properly), compile it, add headers and captions, and then export it with your desired method.

How much this approach will conflict with your current method, I'm not sure... but I don't understand what your current method is, at the moment...
Thanks for your helping.
Now I have this program how I can start modifying this program to get what I want



HashMap words;  // HashMap object

String[] tokens;  // Array of all words from input file


int[] wordcount=new int[200];

int wordcounter;
int counter;

PFont f;




void setup() {
  size(640, 360);
  words = new HashMap();

  // loading data

  String[] lines = loadStrings("input.txt");
  String allText = join(lines, " ");
  tokens = splitTokens(allText, " ,.?!:;[]-");
 


  for(int i = 0; i < tokens.length; i ++) {
  if(ignoreWord(tokens[i])) {
    println(i);
   
    String[] before = subset(tokens, 0, i);
    String[] after = subset(tokens, min(i + 1, tokens.length), tokens.length - 1 - i);
   
    tokens = concat(before, after);
    i --;
  }
}
  
  f = createFont("Georgia", 36, true);  
}



void draw() {

 
String[] outputText = new String[0]; 

  background(255);
  fill(0);
  
  // Look at words one at a time
  String s = tokens[counter];
  counter = (counter + 1) % tokens.length;

  // Is the word in the HashMap
  if (words.containsKey(s)) {
    // Get the word object and increase the count
    // We access objects from a HashMap via its key, the String
    Word w = (Word) words.get(s);
    w.count(); 
  } else {
    // Otherwise make a new word
    Word w = new Word(s);
    // And add to the HashMap
    // put() takes two arguments, "key" and "value"
    // The key for us is the String and the value is the Word object
    words.put(s, w);    
  }

  // Make an iterator to look at all the things in the HashMap
  Iterator i = words.values().iterator();

  
  while (i.hasNext()) {
    // Look at each word
    Word w = (Word) i.next();
    
  
     output= append(output, w.word);
     saveStrings("result.txt", output);

      
    }
  } 
 

}
and this the word class

class Word {
  
  int count;
  String word;
  
  Word(String s) {
    word = s;
    count = 1;
  }
  
  void count() {
    count++;
  }

}  

You understand what I want exactly

if i need to create class 

class wordinformation()
{
  int[] wordCount = new int[100];   //number of freq
  string nameword[];                    // name of the word.
  int wordcounte[];                      //times of freq
  string listsentences[];             // list of sentences
  int wordCounter = 0
How i can get number of freq  and print it in the output file. 
How I can print frequent in output file
I need help please

void writeData() {
  PrintWriter writer = createWriter("output.txet");
  writer.println("word(s) ||");
 
    writer.println(TAB + from + " || " + to + ";");
  }
   writer.flush();
  writer.close();
}

You're on the right track...
You would need to loop through all of the words, get each word's data, and then print that.

I see, now, that you already have a class Word...
You need to add the properties in your other class to this...
Thanks for your answering
i add this loop
for (int d = 0; d < tokens.length; d++) 
 {
    //Display the text and data
    y = y + spacing;
    text(d +" My data in the array = " +tokens[d],x,y);

but maybe I add it in wrong place it give me wrong result

Okay, I'm overly confused, now.
Where do all of these variables come from?
Can you put that code snippet into context?

Also, if you want to print the output, why are you using text()?
Copy code


  1. HashMap words;  // HashMap object

  2. String[] tokens;  // Array of all words from input file
  3. int counter;

  4. PFont f;

  5. //====================================================

  6. void setup() {
  7.   size(640, 360);
  8.   words = new HashMap();

  9.   // loading file
  10.   String[] lines = loadStrings("input.txt");
  11.   String allText = join(lines, " ");
  12.   tokens = splitTokens(allText, " ,.?!:;[]-");
  13.   f = createFont("Georgia", 36, true);  

  14. }
  15. //==================================================
  16. void draw() {
  17.   String[] outputText = new String[0]; 
  18.   background(255);
  19.   fill(0);
  20.   
  21.   // Look at words one at a time
  22.   String s = tokens[counter];
  23.   counter = (counter + 1) % tokens.length;
  24.   //================================================

  25.   // Is the word in the HashMap
  26.   if (words.containsKey(s)) {
  27.     // Get the word object and increase the count
  28.     // We access objects from a HashMap via its key, the String
  29.     Word w = (Word) words.get(s);
  30.     w.count(); 
  31.   } else {
  32.     // Otherwise make a new word
  33.     Word w = new Word(s);
  34.     // And add to the HashMap
  35.     // put() takes two arguments, "key" and "value"
  36.     // The key for us is the String and the value is the Word object
  37.     words.put(s, w);    
  38.   }


  39. //===============================================================
  40.   // Make an iterator to look at all the things in the HashMap
  41.   Iterator i = words.values().iterator();

  42.   
  43.   while (i.hasNext()) {
  44.     // Look at each word
  45.     
  46.     //=========================================================
  47.     // Only display words that appear 2 times
  48.     if (w.count >2) {
  49.       
  50.       outputText = append(outputText, w.word);
  51.      saveStrings("result.txt", outputText);

  52.       }
  53.     }
  54.   ///=====================================
  55.   

  56. }
Copy code
  1. and this the word class
  2. class Word {
  3.   
  4.   int count;
  5.   String word;
  6.   
  7.   Word(String s) {
  8.     word = s;
  9.     count = 1;
  10.   }
  11.   
  12.   void count() {
  13.     count++;
  14.   }

  15. }  
I add to the main program but I didn't know where I can call this function
Copy code
  1. void wordinformation() 
  2. {
  3.   
  4. for (Enumeration e = words.containsKey(s) ; e.hasMoreElements() 
  5. {
  6. String name = e.nextElement().toString();
  7. Word w = (w)words.get(name);
  8. println(w.txt + ":" + w.count);
  9. }
  10. }
  11.  


Okay, I see...

Your function is sort of buggy, you might want to sort that out...
Just call it whenever you want to print the data. Perhaps inside mousePressed(), or something like that...
there is problem in this sentence 
Copy code
  1. String[] lines = loadStrings("input.txt");
    println(“there are “ + lines.length + ” lines”);

    I need to print this in the same output file 
    How i can do that


Create lines globally, or some variable to store the number of lines; then, inside your printing function, add code to print this number.
the error said unexpected char'\'
where is the problem for this line
Copy code
  1. println(“there are “ + lines.length + ” lines”);

You're using the wrong type of quotes, they're curly...
Retype it...
I but global variable but I still have error
Can you please help me  run this program and tell me where is my problem
What program?
The code you posted above doesn't have any of those errors...
I could not understand 
but when I need to add this function 
Copy code
  1. Copy code
    1. void wordinformation() 
    2. {
    3.   
    4. for (Enumeration e = words.containsKey(s) ; e.hasMoreElements() 
    5. {
    6. String name = e.nextElement().toString();
    7. Word w = (w)words.get(name);
    8. println(w.s+ ":" + w.count);
    9. }
    10. }
  2. where I can call this function to print frequent and count in the output file
Okay.

The one-line piece of code you pasted above is using curly quotes instead of regular quotes.
This is the correct code:

Copy code
  1. println("there are " + lines.length + " lines");
Your function there...
This code produces no formatting errors (as far as I can tell):

Copy code
  1. void wordinformation() {
  2.   for (Enumeration e = words.containsKey(s); e.hasMoreElements();) {
  3.     String name = e.nextElement().toString();
  4.     Word w = (w)words.get(name);
  5.     println(w.s+ ":" + w.count);
  6.   }
  7. }
Thanks so much about your answering I respect that but my problem where I can call  this function  void wordinformation() in my code to give me the output.

the error for this function can't convert from Boolean to  Enumeration 

I want to put the output in text file for both words and the count 
Copy code
  1. String lines[];
  2. String list[];
  3. //================================================= 
  4. void setup() {
  5.   lines = loadStrings("input.txt");
  6.   
  7.   println("there are " + lines.length + " lines");
  8.  
  9.   Words words = new Words();
  10.  
  11.   for (int i=0; i < lines.length; i++) 
  12.   {
  13.     list = split(lines[i]);
  14.     for (int j=0; j < list.length; j++) {
  15.       words.addWord(list[j]);
  16.     }
  17.   }
  18.   words.printWords();
  19. }
  20.  
  21. class Words {
  22.  Hashtable ht=new Hashtable();
  23. //======================================================== 
  24.  void addWord(String s) {
  25.    Word word;
  26.    if (ht.containsKey(s)) {
  27.      word = (Word)ht.get(s);
  28.      word.count++;   
  29.    } else {
  30.      word = new Word(s);     
  31.    }
  32.    ht.put(s,word); 
  33.  }
  34. //=========================================================== 
  35.  void printWords() {
  36.    for (Enumeration e = ht.keys() ; e.hasMoreElements() ;)
  37.    {
  38.      String name = e.nextElement().toString();
  39.      Word word = (Word)ht.get(name);
  40.      println(word.s + ": " + word.count);
  41.    }   
  42.   }
  43. }
  44.  //================================================
  45. class Word {
  46.   public String s;
  47.   public int
  48.   count = 1;
  49.   Word(String s) {
  50.     this.s = s;
  51.   }
  52. }
please help me to solve this problem

Okay... I've actually looked at how to write Enumerations, now, and I think the correct code for the function is the following:

Copy code
  1. void wordinformation() {
  2.   for (Enumeration e = words.elements(); e.hasMoreElements();) {
  3.     String name = e.nextElement().toString();
  4.     Word w = (w)words.get(name);
  5.     println(w.s+ ":" + w.count);
  6.   }
  7. }

Your code looks good, all except for line 14.
It should read:

Copy code
  1. list = splitTokens(lines[i], " ,.?!:;[]-");

You could potentially add more split tokens, but it works as is...

Also, you might consider ignoring uppercase vs lowercase...
See String.toLowerCase()...

EDIT: You want to put the output into the separate text file...
Go through and change all of the print statements to print to the text file...

You may not even need to create a specific function for it, although you can build on that approach differently:

You can put all of the printed data into a big String, and then print that in your function...
Thanks for your time
Is this correct to write to text file 
Copy code
  1. void printWords() {
  2.    for (Enumeration e = ht.keys() ; e.hasMoreElements() ;)
  3.    {
  4.      PrintWriter writer = createWriter("result.txt");
  5.      writer.println("This is my data");
  6.      String name = e.nextElement().toString();
  7.      Word word = (Word)ht.get(name);
  8.       writer.println(word.s + ": " + word.count);
  9.    }   
  10.   }
  11. }

How about if I use this function
Copy code
  1. void writeData() {
  2.   PrintWriter writer = createWriter("output.txt");
  3.   writer.println("This is my data");
  4.   for (int i = 0; i < list.length; i++) {
  5.     String w= "\"" + word.s + "\"";
  6.     String c= "\"" + word.count + "\"";
  7.     writer.println(TAB + w+ " :: " + c+ ";");
  8.   }
  9.   writer.flush();
  10.   writer.close();
  11. }
I think the problem in 
Copy code
  1.  String w= "\"" + word.s + "\"";
  2.     String c= "\"" + word.count + "\"";
You're looping through list, although referencing word.
There's something wrong...

I think your first function should work, if you get rid of that last " }"...
first function works good after you correct to me line 14 but it print the output on the screen I need the output in text file
Really?
The below function prints to the console?

Copy code
  1. void printWords() {
  2.    for (Enumeration e = ht.keys() ; e.hasMoreElements() ;)
  3.    {
  4.      PrintWriter writer = createWriter("result.txt");
  5.      writer.println("This is my data");
  6.      String name = e.nextElement().toString();
  7.      Word word = (Word)ht.get(name);
  8.       writer.println(word.s + ": " + word.count);
  9.    }  
  10.   }
  11. }
yes, but How I can print to text file?

I thought that that was printing to a text file...
You can try saveStrings() (in name of the original topic)...
Copy code
  1.  saveStrings("result.txt", list);
It is works for the words,but doesn't work for number of frequent 
Copy code
  1.       saveStrings("result.txt", word.count);// there are error

I need the word and their frequent in the same file 
You have to format the String array properly...
In your function, all you have to do is change your print calls to add values to an already created String array. Then, save the String array...
can you explain please how to add values to string array
Copy code
  1.  void printWords()
  2.  {
  3.    for (Enumeration e = ht.keys() ; e.hasMoreElements() ;)
  4.  {
  5.      String name = e.nextElement().toString();
  6.      Word word = (Word)ht.get(name);
  7.      println(word.txt + " : " + word.count);
  8.       }   
  9.   }
  10. }
  11.  
I am really confused can you help me to print the output to text file 

That would look something like this:

Copy code
  1. void printWords() {
  2.   String[] output = ""; //Create a String array to store the output
  3.  
  4.   for (Enumeration e = ht.keys(); e.hasMoreElements();) {
  5.     String name = e.nextElement().toString();
  6.     Word word = (Word)ht.get(name);
  7.     output += (word.txt + " : " + word.count + "\n"); //Instead of printing the output, add it to the String array... the "\n" is a newline character
  8.   }
  9.  
  10.   saveStrings("result.txt", output); //Save the output
  11. }

There are error for this line
Copy code
  1.  String[] output = ""; //Create a String array to store the output
can't  convert from string to string>>>why?
Because that's not a valid syntax for making an array... calsign made a little mistake there.

BTW, don't use Hashtable, it is an outdated class, use a typed HashMap instead.
OK, here is a working version of the code you found, with less unneeded global variables and a more modern usage of the collections.
Copy code
  1. void setup() {
  2.   String[] lines = loadStrings("H:/Temp/Test.txt");
  3.  
  4.   println("there are " + lines.length + " lines");
  5.  
  6.   Words words = new Words();
  7.  
  8.   for (int i = 0; i < lines.length; i++)
  9.   {
  10.     // Get rid of non-alphabetical chars
  11.     String line = lines[i].replaceAll("[^a-zA-Z '-]", " ");
  12.     String[] list = split(line, ' ');
  13.     for (int j = 0; j < list.length; j++) {
  14.       words.addWord(list[j]);
  15.     }
  16.   }
  17.   words.printWords();
  18.   words.exportWords("H:/Temp/output.txt");
  19.   exit();
  20. }
  21.  
  22. class Words {
  23.  HashMap<String, Word> words = new HashMap<String, Word>();
  24.  
  25. //========================================================
  26.  void addWord(String s) {
  27.    if (words.containsKey(s)) {
  28.      Word word = words.get(s);
  29.      word.count++;  
  30.    } else {
  31.      Word word = new Word(s);
  32.      words.put(s, word);
  33.    }
  34.  }
  35.  
  36. //===========================================================
  37.   void printWords() {
  38.     Collection<Word> values = words.values();
  39.     for (Word word : values)
  40.     {
  41.       // Exclude rare and too short words
  42.       if (word.count > 1 && word.s.length() > 2)
  43.       {
  44.         println(word.s + ": " + word.count);
  45.       }
  46.     }
  47.   }
  48.  
  49.   void exportWords(String file) {
  50.     Collection<Word> values = words.values();
  51.     int nb = values.size();
  52.     String[] allWords = new String[nb];
  53.     int c = 0;
  54.     for (Word word : values)
  55.     {
  56.       if (word.count > 1 && word.s.length() > 2)
  57.       {
  58.         allWords[c++] = word.s + ": " + word.count;
  59.       }
  60.     }
  61.     String[] out = Arrays.copyOf(allWords, c);
  62.     saveStrings(file, out);
  63.   }
  64. }
  65.  
  66. //================================================
  67. class Word {
  68.   public String s;
  69.   public int count = 1;
  70.  
  71.   Word(String s) {
  72.     this.s = s;
  73.   }
  74. }

While I was at it, I renamed some stuff, and added stop words management.
See complete sketch at http://bazaar.launchpad.net/~philho/+junk/Processing/view/head:/_QuickExperiments/_Java/_Collections/CountingWords/CountingWords.pde
wooooow!

Thanks so so much 
if I need save in output text the number of sentence that include the word 


               
Copy code
  1.   String[] sentences ;

  2.   for (String sentence : sentences)
  3.   {
  4.     println(sentence);
  5.   }
How i can put the sentences in  String[] sentences ;
I have to know the sentence if I find (.) the end of the sentence
You want to create a String array containing all of the sentences?
Like this?

Copy code
  1. sentences = splitTokens(inputText, ".!?"); //Split the input by periods ".", exclamation points "!", and question marks "?"

Replace inputText with what you need to split...
You may need to consolidate an array of Strings...
I need to split lines when I find periods"."
for example 

Many applications require a dynamic set that supports only the dictionary operations INSERT, SEARCH, and DELETE . For example, a compiler that translates a programming language maintains a symbol table, in which the keys of elements are arbitrary character strings corresponding to identifiers in the language .

the first sentence 
Many applications require a dynamic set that supports only the dictionary operations INSERT, SEARCH, and DELETE.
the second sentence 
For example, a compiler that translates a programming language maintains a symbol table, in which the keys of elements are arbitrary character strings corresponding to identifiers in the language .

I want to print where the frequent appear in any sentence 
Then just remove the exclamation point and the question mark...

Copy code
  1. sentences = split(inputText, '.');
when i  wrote
Copy code
  1. String[] sentences ;

  2.      sentences = splitTokens("input.txt", "."); //Split the input by periods "."
  3.     for (String sentence : sentences)
  4.   {
  5.     println(sentence);
  6.   }
when i test did not give me the sentence that included in the text

That will return {"input", "txt"}.
You need to actually load the file, consolidate all of the loaded Strings into one String, and then pass the result of that to splitTokens()...

Like this:

Copy code
  1. String[] loadedFile = loadStrings("input.txt"); //Load the file
  2. String input = ""; //Initialize the consolidated String

  3. for(int i = 0; i < loadedFile.length; i ++) input += loadedFile[i]; //Consolidate the loaded file into one String

  4. String[] sentences = splitTokens(input, "."); //Split the String into sentences
Yes it's work perfectly
Thanks

Here, you have a quite different problem. In the first case, you had to count the word occurrences, regardless of where they are. Here, brutal force splitting is enough.
Now, you have to distinguish were each word occurrence is located! You have to use a smarter split strategy.

Mmm, it is doable.
I would join all the lines into one string, then split along the full stop. And then, you can remove from each sentence of the resulting array the punctuation as I did, and split them on the spaces, as before.
I would change the Word class: remove the count, and add an array list of integers: ArrayList<Integer>
Each time you add a word, include the number of the sentence it is located in. And instead of incrementing count, add this number to the ArrayList. Thus, for each word, you will get a list of all the sentence numbers it has been found in. And the size of the list is the count of words.

[EDIT] Ah, answer is a bit late (I kept the topic open for some time...). Note that you have the join() function, doing that operation more efficiently than shown above: it is rarely a good idea to concatenate strings in a loop, it is inefficient as it generates lot of garbage. join() uses a StringBuillder (well, actually its older cousin, StringBuffer) to do it efficiently.
in the output file i want to add another column that include the number of sentence that include this word


for example
table     2     sentence1,sentence2


Copy code
  1.   class Word
  2.   {
  3.     String w;
  4.     ArrayList<Integer> sentenceNbs = new ArrayList<Integer>();

  5.     Word(String s, int pos)
  6.     {
  7.       w = s;
  8.       add(pos);
  9.     }
  10.  
  11.     void add(int pos)
  12.     {
  13.       sentenceNbs.add(pos);
  14.     }

  15.     // Allows to get a human readable string out of the object
  16.     String toString()
  17.     {
  18.       return w + "\t" + sentenceNbs.size() + "\t" + sentenceNbs;
  19.     }
  20.   }
Used as:
Copy code
  1.     Word word = words.get(w); // Get it from the list
  2.     if (word == null) // Not found
  3.     {
  4.       // Create a new word
  5.       word = new Word(w, pos);
  6.       words.put(w, word);
  7.     }
  8.     else
  9.     {
  10.       // Update it directly in the hash map
  11.       word.add(pos);
  12.     }
in WordList.add()
Untested, and need, of course, more work elsewhere.
Here we go again...

In the Word class, add a value containing all of the appearing sentences...
Probably a String, to make it simple...

Every time that you add an occurrence to the word, append the current sentence to that String.

When you output the file, add this value to the end of each corresponding line...
I understand what i need to add for word class
i add the code above,but where i can add this update
Copy code
  1. Copy code
    1. Word word = words.get(w); // Get it from the list
    2.     if (word == null) // Not found
    3.     {
    4.       // Create a new word
    5.       word = new Word(w, pos);
    6.       words.put(w, word);
    7.     }
    8.     else
    9.     {
    10.       // Update it directly in the hash map
    11.       word.add(pos);
    12.     }

in WordList.add()
It replaces the similar code. But you have to pass pos as parameter, etc., as explained.


it give me error said can not find anything names pos
It is still has error

That's what I wrote... I just don't have the time to write it for you, you have to understand the code, adapt it as I described above, and fix the problem yourself: pos is intended to be the sentence number where the word has been found. Meaning you parse as described, and when adding word of each sentence, you pass this pos as additional parameter.
Thanks,I understand the code I am trying if it doesn't work I will come back
New error for this line
Copy code
  1.   WordList.add()
unexpected token (

Does the function call have any parameters?
Can you show the line in context?
Copy code
  1.  WordList.add()
  2.   {
  3.     Word word = words.get(w); // Get it from the list
  4.     if (word == null) // Not found
  5.     {
  6.       // Create a new word
  7.       word = new Word(w, pos);
  8.       words.put(w, word);
  9.     }
  10.     else
  11.     {
  12.       // Update it directly in the hash map
  13.       word.add(pos);
  14.     }
  15.   }
  16.   
This is not the whole program
This is the whole program maybe I add it in wrong place
Copy code
  1. String[] stopWordList = { "all", "and", "are", "as", "at", "be", "but", "by", "do", "done,",
  2.   "for", "from", "he", "her", "him", "in", "is", "it", "of", "or", "our", "me", "my", "no", "not", "on",
  3.   "she", "so", "that", "the", "there", "they", "this", "to", "too", "you", "your"
  4. }; // And so on...

  5. void setup()
  6. {
  7.   String[] lines = loadStrings("input.txt");

  8.   println("Read " + lines.length + " lines");

  9.   WordList words = new WordList();
  10.   for (String line : lines)
  11.   {
  12.     // Get rid of non-alphabetical chars
  13.     line = line.replaceAll("[^a-zA-Z -]", " ");
  14.     // Collapse multiple spaces into one
  15.     line = line.replaceAll(" +", " ").toLowerCase();
  16.     String[] wordList = split(line, ' ');
  17.     // Add the words of the line
  18.     for (String word : wordList)
  19.     {
  20.       words.add(word);
  21.     }
  22.   }
  23.   words.print();
  24.   words.export("output.txt");
  25.   exit();
  26. }

  27. class WordList
  28. {
  29.   // Simple class to store a word and its count in a collection
  30.   // Internal as we don't need to expose it to the outer world...
  31.    class Word
  32.   {
  33.     String w;
  34.     ArrayList<Integer> sentenceNbs = new ArrayList<Integer>();

  35.     Word(String s, int pos)
  36.     {
  37.       w = s;
  38.       add(pos);
  39.     }
  40.  
  41.     void add(int pos)
  42.     {
  43.       sentenceNbs.add(pos);
  44.     }

  45.     // Allows to get a human readable string out of the object
  46.     String toString()
  47.     {
  48.       return w + "\t" + sentenceNbs.size() + "\t" + sentenceNbs;
  49.     }
  50.  
  51.   WordList.add()
  52.   {
  53.     Word word = words.get(w); // Get it from the list
  54.     if (word == null) // Not found
  55.     {
  56.       // Create a new word
  57.       word = new Word(w, pos);
  58.       words.put(w, word);
  59.     }
  60.     else
  61.     {
  62.       // Update it directly in the hash map
  63.       word.add(pos);
  64.     }
  65.   }
  66.   
  67.   
  68.   // List of words and their count, with unicity guarantee
  69.   HashMap<String, Word> words = new HashMap<String, Word>();
  70.   // List of stop words, with quick check if a given string is part of this list
  71.   HashSet<String> stopWords = new HashSet<String>();

  72.   WordList()
  73.   {
  74.     // Build the stop word structure
  75.     stopWords.addAll(Arrays.asList(stopWordList));
  76.     // Simple check...
  77.     println(stopWords);
  78.   }

  79.   // Add a word
  80.   void add(String w)
  81.   {
  82.     if (w.length() < 2)
  83.       return; // Exclude 0 or 1 sized words
  84.     if (stopWords.contains(w))
  85.       return; // Exclude known stop words

  86.     Word word = words.get(w); // Get it from the list
  87.     if (word == null) // Not found
  88.     {
  89.       // Create a new word
  90.       word = new Word(w);
  91.       words.put(w, word);
  92.     }
  93.     else
  94.     {
  95.       // Update it directly in the hash map
  96.       word.count++;
  97.     }
  98.   }

  99.   // Print out the list on the console
  100.   void print()
  101.   {
  102.     // List of the values
  103.     Collection<Word> values = words.values();
  104.     for (Word word : values)
  105.     {
  106.       // Print frequent words
  107.       if (word.count > 1)
  108.       {
  109.         println(word); // Calls toString() automatically
  110.       }
  111.     }
  112.   }

  113.   // Export the list to a file
  114.   void export(String file)
  115.   {
  116.     Collection<Word> values = words.values();
  117.     int nb = values.size();
  118.     String[] allWordList = new String[nb];
  119.     int c = 0;
  120.     for (Word word : values)
  121.     {
  122.       if (word.count > 1)
  123.       {
  124.         allWordList[c++] = word.toString(); // Must call explicitly here
  125.       }
  126.     }
  127.     // Make a copy of the array, truncated to the real size
  128.     String[] out = Arrays.copyOf(allWordList, c);
  129.     // and save it to the file
  130.     saveStrings(file, out);
  131.   }
  132. }
Are you trying to declare a function?
Are you trying to call a function?

No wonder the compiler says something is wrong, that is not a piece of valid code...

What are you trying to do?
I need to present the number of sentence that include the frequent word in the same output file 
PhiLho modified  this part above to me but I think I add it in wrong place in the code. 

I'm starting to understand your situation...
I'm pretty sure that PhiLho meant to put that code inside WordList's add() function...
I put it   inside  WordList 's  add()  function but it is still error there

calsign is right, WordList.add() is a traditional notation to mean WordList class' add() method!
This means that you must change the initial code in the method declared with void add(String w)
You replace the similar looking code with the new one.
Thanks so much PhiLho I did all of these step but I still have error.
You still have an error... can you be more specific?
The error in variable  pos I know pos position for the word but the program can not find anything named pos where i should but the declaration for it .
This is the program
Copy code
  1. String[] stopWordList = { "all", "and", "are", "as", "at", "be", "but", "by", "do", "done,",
  2.   "for", "from", "he", "her", "him", "in", "is", "it", "of", "or", "our", "me", "my", "no", "not", "on",
  3.   "she", "so", "that", "the", "there", "they", "this", "to", "too", "you", "your"
  4. }; // And so on...

  5. void setup()
  6. {
  7.   String[] lines = loadStrings("input.txt");

  8.   println("Read " + lines.length + " lines");

  9.   WordList words = new WordList();
  10.   for (String line : lines)
  11.   {
  12.     // Get rid of non-alphabetical chars
  13.     line = line.replaceAll("[^a-zA-Z -]", " ");
  14.     // Collapse multiple spaces into one
  15.     line = line.replaceAll(" +", " ").toLowerCase();
  16.     String[] wordList = split(line, ' ');
  17.     // Add the words of the line
  18.     for (String word : wordList)
  19.     {
  20.       words.add(word);
  21.     }
  22.   }
  23.   words.print();
  24.   words.export("output.txt");
  25.   exit();
  26. }

  27. class WordList
  28. {
  29.   // Simple class to store a word and its count in a collection
  30.   // Internal as we don't need to expose it to the outer world...
  31.   class Word
  32.   {
  33.     String w;
  34.     ArrayList<Integer> sentenceNbs = new ArrayList<Integer>();

  35.     Word(String s, int pos)
  36.     {
  37.       w = s;
  38.       add(pos);
  39.     }
  40.  
  41.     void add(int pos)
  42.     {
  43.       sentenceNbs.add(pos);
  44.     }

  45.     // Allows to get a human readable string out of the object
  46.     String toString()
  47.     {
  48.       return w + "\t" + sentenceNbs.size() + "\t" + sentenceNbs;
  49.     }
  50.   }
  51.   // List of words and their count, with unicity guarantee
  52.   HashMap<String, Word> words = new HashMap<String, Word>();
  53.   // List of stop words, with quick check if a given string is part of this list
  54.   HashSet<String> stopWords = new HashSet<String>();

  55.   WordList()
  56.   {
  57.     // Build the stop word structure
  58.     stopWords.addAll(Arrays.asList(stopWordList));
  59.     // Simple check...
  60.     println(stopWords);
  61.   }

  62.   // Add a word
  63.   void add(String w)
  64.   {
  65.     if (w.length() < 2)
  66.       return; // Exclude 0 or 1 sized words
  67.     if (stopWords.contains(w))
  68.       return; // Exclude known stop words

  69.     Word word = words.get(w); // Get it from the list
  70.              int pos;

  71.     if (word == null) // Not found
  72.     {


  73.       // Create a new word

  74.       word = new Word(w, pos);
  75.       words.put(w, word);
  76.     }
  77.     else
  78.     {
  79.       // Update it directly in the hash map
  80.       word.add(pos);
  81.   }
  82.   }

  83.   // Print out the list on the console
  84.   void print()
  85.   {
  86.     // List of the values
  87.     Collection<Word> values = words.values();
  88.     for (Word word : values)
  89.     {
  90.       // Print frequent words
  91.       if (word.count > 1)
  92.       {
  93.         println(word); // Calls toString() automatically
  94.       }
  95.     }
  96.   }

  97.   // Export the list to a file
  98.   void export(String file)
  99.   {
  100.     Collection<Word> values = words.values();
  101.     int nb = values.size();
  102.     String[] allWordList = new String[nb];
  103.     int c = 0;
  104.     for (Word word : values)
  105.     {
  106.       if (word.count > 1)
  107.       {
  108.         allWordList[c++] = word.toString(); // Must call explicitly here
  109.       }
  110.     }
  111.     // Make a copy of the array, truncated to the real size
  112.     String[] out = Arrays.copyOf(allWordList, c);
  113.     // and save it to the file
  114.     saveStrings(file, out);
  115.   }
  116. }

On line 81, you declare pos, but don't give it a value; then, you try to call a function using this nonexistent value.
Quite frankly, I don't know what the value is supposed to be... but that's why you're getting the error...
it is not important i can remove this in line 81
and the position for the sentence it is sentence number 1 or number 2
The exact error in line 65
Copy code
  1.       word = new Word(w, pos);
it said the local variable pos may not have been initialized 

Yes... I thought I just explained that pos has to be assigned a value...

Well. I'll go a little bit further...
pos has to be assigned either 1 or 2, depending on which sentence it occurs in.
Thanks so much for your time and your explanation ,How I can changed it help me please,because I tired adding something doesn't work 
Okay... This is complicated...

You need to change the parameters of your WordList.add() function to pass the sentence number...
Inside that function, assign pos to be this newly passed number.

When you call the function, add the line number... you're going to have to change the format of your for loop...

Revised Code:

Copy code
  1. String[] stopWordList = { "all", "and", "are", "as", "at", "be", "but", "by", "do", "done,",
  2.   "for", "from", "he", "her", "him", "in", "is", "it", "of", "or", "our", "me", "my", "no", "not", "on",
  3.   "she", "so", "that", "the", "there", "they", "this", "to", "too", "you", "your"
  4. }; // And so on...

  5. void setup()
  6. {
  7.   String[] lines = loadStrings("input.txt");
  8.   println("Read " + lines.length + " lines");
  9.   WordList words = new WordList();
  10.   for (String line : lines)
  11.   {
  12.     // Get rid of non-alphabetical chars
  13.     line = line.replaceAll("[^a-zA-Z -]", " ");
  14.     // Collapse multiple spaces into one
  15.     line = line.replaceAll(" +", " ").toLowerCase();
  16.     String[] wordList = split(line, ' ');
  17.     // Add the words of the line
  18.     for (int i = 0; i < wordList.length; i ++) //(EDITED) Change the format so that we have an iterator
  19.     {
  20.       words.add(wordList[i], i); //(EDITED) Pass the new value
  21.     }
  22.   }
  23.   words.print();
  24.   words.export("output.txt");
  25.   exit();
  26. }

  27. class WordList
  28. {
  29.   // Simple class to store a word and its count in a collection
  30.   // Internal as we don't need to expose it to the outer world...
  31.   class Word
  32.   {
  33.     String w;
  34.     ArrayList<Integer> sentenceNbs = new ArrayList<Integer>();
  35.     Word(String s, int pos)
  36.     {
  37.       w = s;
  38.       add(pos);
  39.     }
  40.  
  41.     void add(int pos)
  42.     {
  43.       sentenceNbs.add(pos);
  44.     }
  45.     // Allows to get a human readable string out of the object
  46.     String toString()
  47.     {
  48.       return w + "\t" + sentenceNbs.size() + "\t" + sentenceNbs;
  49.     }
  50.   }
  51.   // List of words and their count, with unicity guarantee
  52.   HashMap<String, Word> words = new HashMap<String, Word>();
  53.   // List of stop words, with quick check if a given string is part of this list
  54.   HashSet<String> stopWords = new HashSet<String>();
  55.   WordList()
  56.   {
  57.     // Build the stop word structure
  58.     stopWords.addAll(Arrays.asList(stopWordList));
  59.     // Simple check...
  60.     println(stopWords);
  61.   }
  62.   // Add a word
  63.   void add(String w, int sentenceNum) //(EDITIED) Include the new parameter
  64.   {
  65.     if (w.length() < 2)
  66.       return; // Exclude 0 or 1 sized words
  67.     if (stopWords.contains(w))
  68.       return; // Exclude known stop words
  69.     Word word = words.get(w); // Get it from the list
  70.     int pos = sentenceNum; //(EDITED) Assign the position
  71.     if (word == null) // Not found
  72.     {
  73.       // Create a new word
  74.       word = new Word(w, pos);
  75.       words.put(w, word);
  76.     }
  77.     else
  78.     {
  79.       // Update it directly in the hash map
  80.       word.add(pos);
  81.   }
  82.   }
  83.   // Print out the list on the console
  84.   void print()
  85.   {
  86.     // List of the values
  87.     Collection<Word> values = words.values();
  88.     for (Word word : values)
  89.     {
  90.       // Print frequent words
  91.       if (word.count > 1)
  92.       {
  93.         println(word); // Calls toString() automatically
  94.       }
  95.     }
  96.   }
  97.   // Export the list to a file
  98.   void export(String file)
  99.   {
  100.     Collection<Word> values = words.values();
  101.     int nb = values.size();
  102.     String[] allWordList = new String[nb];
  103.     int c = 0;
  104.     for (Word word : values)
  105.     {
  106.       if (word.count > 1)
  107.       {
  108.         allWordList[c++] = word.toString(); // Must call explicitly here
  109.       }
  110.     }
  111.     // Make a copy of the array, truncated to the real size
  112.     String[] out = Arrays.copyOf(allWordList, c);
  113.     // and save it to the file
  114.     saveStrings(file, out);
  115.   }
  116. }
I am so sorry but another error appear  in line 93
Copy code
  1.       if (word.count > 2)

      word.count  con not be resolved or is not field 

Yes...
That's something else that was present in your old code as well, though...

Try replacing it with word. sentenceNbs.size()...
It should do the same thing...
wooooow
Thanks so so much it is works very good thanks for your helping and this is support me a lot to continue learning
Thanks a gain
I have another idea What I am trying to do is load a text document which has lots of lines of text and i want to remove common word and delete the space for this word that i removed but I need to save the sentence without change just remove the word that I need to remove
Copy code
  1. String[] tokens;  // Array of all words from input file
  2. PFont f;

  3. String[] ignore = { "only","to", "For example","can","for","of","is","as","a","the","that","an", "the", "i", "it", "you", "and", "to","in","on","you","they","for","from","to","which", };

  4. boolean ignoreWord(String what) {
  5.   for (int i = 0; i < ignore.length; i++) {
  6.   
  7.    if (what.equals(ignore[i])) {
  8.           if (what.toLowerCase().equals(ignore[i])) {

  9.       return true;
  10.     }
  11.   }
  12.   return false;
  13. }

  14. void setup() {

  15.       String[] output = new String[0]; 

  16.   // Load file and chop it up
  17.   String[] lines = loadStrings("input.txt");
  18.   
  19.    for(int i = 0; i < lines.length; i ++) 
  20.   {
  21.     
  22.   if(ignoreWord(lines[i])) 
  23.   {
  24.     String A = lines[i];
  25.     A = A.replace(lines[i],"");
  26.     println(A);
  27.      
  28.     String[] before = subset(tokens, 0, i);
  29.     String[] after = subset(tokens, min(i + 1, tokens.length), tokens.length - 1 - i);
  30.    
  31.     tokens = concat(before, after);
  32.     i --;
  33.     
  34.       output = append(outputText,"what i shoud to put here");
  35.       saveStrings("result.txt", output);  

  36.   
  37.   f = createFont("Georgia", 36, true);  
  38. }
first I put all the words that i need to remove in array then I load the text file after that i need to read the text line by line if i find one of these words just remove it and remove the space for it and keep the output in text file(text included the sentence in same arrange but without common word)
Hmm... I don't have too much time right now, but here's a revised version of your code that doesn't cause any errors and should put you on the right track:

Copy code
  1. String[] tokens;  // Array of all words from input file

  2. String[] ignore = {
  3.   "only", "to", "For example", "can", "for", "of", "is", "as", "a", "the", "that", "an", "the", "i", "it", "you", "and", "to", "in", "on", "you", "they", "for", "from", "to", "which",
  4. };

  5. boolean ignoreWord(String what) {
  6.   for (int i = 0; i < ignore.length; i++) {
  7.     if (what.toLowerCase().equals(ignore[i])) {
  8.       return true;
  9.     }
  10.   }
  11.  
  12.   return false;
  13. }

  14. void setup() {
  15.   String[] output = new String[0];
  16.   // Load file and chop it up
  17.   String[] lines = loadStrings("input.txt");
  18.   for(int i = 0; i < lines.length; i ++) {
  19.    
  20.     if (ignoreWord(lines[i]))
  21.     {
  22.       String A = lines[i];
  23.       A = A.replace(lines[i], "");
  24.       println(A);
  25.       String[] before = subset(tokens, 0, i);
  26.       String[] after = subset(tokens, min(i + 1, tokens.length), tokens.length - 1 - i);
  27.       tokens = concat(before, after);
  28.       i --;
  29.       output = append(output, "what i shoud to put here");
  30.     }
  31.   }
  32.  
  33.   saveStrings("result.txt", output);
  34. }

HINT: You'll need to loop through each String in the loaded array of Strings to match for words...
error in line 7 can not find anything named string
Copy code
  1. // string array included all the common words

  2. String[] ignore = {"only", "to", "For example", "can", "for", "of", "is", "as", "a", "the", "that", "an", "the", "i", "it", "you", "and", "to", "in", "on", "you", "they", "for", "from", "to", "which",
  3. };
  4. // function to  check if common word and replace it
  5. string  ignoreWord(String a)
  6. {
  7.   for (int i = 0; i < ignore.length; i++) {
  8.     if (a.toLowerCase().equals(ignore[i])) {
  9.       return ( ignore[i] = ignore[i].replace(ignore[i], ""));
  10.     }
  11.   }
  12.  
  13.   return ;
  14. }


  15. void setup() {

  16.   String[] output = new String[0];
  17.   // Load file and chop it up
  18.   
  19.   String[] lines = loadStrings("input.txt");
  20.   //for to go through all words 
  21.   for(int i = 0; i < lines.length; i ++) 
  22.   {
  23.        if (ignoreWord(lines[i]))
  24.     {
  25.       println(lines[i]);
  26.       i --;
  27.        }
  28.   }
  29.  
  30.   saveStrings("result.txt", output);
  31. }
That's a really simple error... can you start to fix them on your own?
It's looking for a datatype called " string", but you need " String".
Processing / Java is case sensitive.

The correct code is:

Copy code
  1. String ignoreWord(String a)
the error said the method must return a result of type string
Copy code
  1. String ignoreWord(String a)

  2. {
  3.   for (int i = 0; i < ignore.length; i++) {
  4.     if (a.toLowerCase().equals(ignore[i])) {
  5.        ignore[i] = ignore[i].replace(ignore[i], " ");
  6.       return ignore[i];
  7.     }
  8.   }
  9.  
  10.   }
I really always try to fix it by myself but sometimes i don't know how i can fix it
Thanks a lot you really help me
Okay... I think PhiLho answered a similar question earlier on in this... long... post...
But here's the rundown:

Yes, you return a String, but not in all circumstances.
What if, for some reason, ignore.length was zero?

It's a simple fix... just add a return statement at the end of the function with either a null or an empty String value...
I wrote this code 
Copy code
  1.   else return ignore[i]=(" "); 
but error said must return result of type string
No... put it at the end of the function, outside the for loop.
it can not find variable i when i put it outside for loop
Copy code
  1.  return ignore[i]=(" ");
You don't need to reference the variable...
The following will suffice:

Copy code
  1. return "";
in check her said can not convert from string to Boolean
Copy code
  1.        if (ignoreWord(lines[i]))
String[] lines = loadStrings("input.txt");
Wait... why are you using a String in the first place?
I'm not sure where that came from...
Try using this function (from the code I posted above):

Copy code
  1. boolean ignoreWord(String what) {
  2.   for (int i = 0; i < ignore.length; i++) {
  3.     if (what.toLowerCase().equals(ignore[i])) {
  4.       return true;
  5.     }
  6.   }
  7.  
  8.   return false;
  9. }

It appears that you're trying to replace the ignored word with a space... but this isn't the place to do that. Instead, do that inside the if statement that checks to see if the word is ignored...
This code print nothing inside result file
where the problem
Copy code
  1. String[] tokens;  // Array of all words from input file

  2. String[] ignore = {
  3.   "only", "to", "For example", "can", "for", "of", "is", "as", "a", "the", "that", "an", "the", "i", "it", "you", "and", "to", "in", "on", "you", "they", "for", "from", "to", "which",
  4. };


  5. boolean ignoreWord(String what) {
  6.   for (int i = 0; i < ignore.length; i++) {
  7.     if (what.toLowerCase().equals(ignore[i])) {
  8.       return true;
  9.     }
  10.   }
  11.  
  12.   return false;
  13. }

  14. //===========================================

  15. void setup() {
  16.   String[] output = new String[0];
  17.   // Load file and chop it up
  18.   String[] lines = loadStrings("input.txt");
  19.   for(int i = 0; i < lines.length; i ++) {
  20.    
  21.     if (ignoreWord(lines[i]))
  22.     {
  23.       String A = lines[i];
  24.       A = A.replace(lines[i], "");
  25.       println(A);
  26.       String[] before = subset(tokens, 0, i);
  27.       String[] after = subset(tokens, min(i + 1, tokens.length), tokens.length - 1 - i);
  28.       tokens = concat(before, after);
  29.       i --;
  30.       output = append(output, "");
  31.     }
  32.   }
  33.  
  34.   saveStrings("result.txt", output);
  35. }

That's because you're saving output, which is an empty String, not lines...
Also, unless your words are separated onto different lines in the file, the ignoreWord() function; thus, the entire program, will not work. You should split up each line, test each word, and then put the remains back together and save it...
I follow your advise it is works but i have error about what I should but in the output file line 44
Copy code
  1. String[] tokens;  // Array of all words from input file

  2. String[] ignore = {"only", "to", "For example", "can", "for", "of", "is", "as", "a", "the", "that", "an", "the", "i", "it", "you", "and", "to", "in", "on", "you", "they", "for", "from", "to", "which",
  3. };
  4. PFont f;


  5. boolean ignoreWord(String what) {
  6.   for (int i = 0; i < ignore.length; i++) {
  7.     if (what.toLowerCase().equals(ignore[i])) {
  8.       return true;
  9.     }
  10.   }
  11.  
  12.   return false;
  13. }

  14. //===========================================

  15. void setup() 
  16. {
  17.   String[] output = new String[0];
  18.   // Load file and chop it up
  19.   String[] lines = loadStrings("input.txt");
  20.   String allText = join(lines, " ");
  21.   tokens = splitTokens(allText, " ,.?!:;[]-");
  22.   for(int i = 0; i < tokens.length; i ++) 
  23.   {
  24.      if(ignoreWord(tokens[i])) 
  25.   {
  26.      tokens[i] = tokens[i].replace(tokens[i], "");
  27.       println(i);
  28.    
  29.     String[] before = subset(tokens, 0, i);
  30.     String[] after = subset(tokens, min(i + 1, tokens.length), tokens.length - 1 - i);
  31.    
  32.     tokens = concat(before, after);
  33.     i --;
  34.   }
  35. }
  36.   
  37.   f = createFont("Georgia", 36, true);  
  38.   output = append(output, tokenes[i]);
  39.    saveStrings("result.txt", output);

  40.     }
  41.  
output = append(output, tokenes[i]);
tokenes doesn't exist in your program...
I changed to 
Copy code
  1.   output = append(output, tokens);
can not convert from object to string
I changed to 
Copy code
  1.   output = append(output, tokens[i]);
but it give me only one word in the output file
the output file that i want the same input file just common words removed from it .but the sentence still the same arrangement how can i do it 
What you want is pretty complicated...
I don't think your current approach is going to work, though, unfortunately.
So far, in this thread, you've posted code, we've helped you to fix errors, and you've implemented our advice...
I think something different is necessary.

The problem that you have right now is mapping the original words to be replaced in the same position when you output the file. This is doable, although it wouldn't be very clean... So, therefor, you need:

A class to store each word (and any punctuation or spaces associated with that word)... and a list of all of the words. Then, you can remove the words that are common from the list, and keep the same formatting...

You would be able to use some of the old code, such as the ignoreWord() function...

I'll stop talking for now...
Can you please help me I don't need to stop learning 
Copy code
  1. WordAnalysis analysis;
  2. }
  3.  void setup() 
  4. {
  5.   analysis = new WordAnalysis();
  6.    String[] lines = loadStrings("input.txt");
  7.    String allText = join(lines, " ");
  8.   String[] wordList = split(allText, " ");
  9.   
  10.   for (int i = 1; i < wordList.length; i++) 
  11.    {
  12.       println(wordList[i]);
  13. }
How i can save the word and  any punctuation or spaces associated with that word and keep the same format for the file
Copy code

    I suggest to make a new topic for questions not directly related to the initial one (even if it is still about manipulating sentences). This thread is already very long, making it hard to manage and discouraging people to help...
    Put a link to this thread, so people can get context if needed.
    Thanks for your suggest I put in more than one forum but no body answer me
    I try before but really no one helpful more than you Philho or calsign I will wait you 
    if your are busy help me please when i discuses with someone i can continue programming .
    Firstly, it's not a good idea to post more than once...
    Quite frankly, you're drawing attention - the bad kind - to yourself.

    I, and probably others, have looked at your posts, but we don't have answers.

    I think what you are attempting is too ambitious for your (no offense) coding skills.
    Short of writing the code for you, we can't help you all that much.
    I just need the last file text to draw the graph but the most important part for me this is text file after that i will try different things because i need to do more things related to this file only this program i want help with it .I try to do it but i don't know how only with this  keeping the same formatting for the text file please.or if you have other links that will be helpful for me.
    I deleted the last answer, as it belongs to the new thread you created. You created a new thread to avoid lengthening more this one, so avoid posting in both, as it makes difficult to focus on one.
    Likewise, I deleted another thread you created (in the wrong section of the forum) as it asked a question that could have been asked on the same thread (the answer is: you have a Word class, you can add as many information as you want inside).
    Lastly, I posted code (have you seen the online version, with more comments?), which should provide 90% of the tools you need to perform your new request.
    It is OK if you have not understood everything there, it was quite dense, with lot of new stuff for you. But if you don't ask questions on the things you haven't understood, you will never learn from it. There is no shame in asking questions, and mastering the tools I gave would make the life simpler for everybody.

    Note that we have a work (or studies), a life, and perhaps different time zones, so don't complain if you have not an answer in the few hours of your post. You made searches in the forum, which is a good idea, but you answered to an old thread with exactly the same code you shown in the https://forum.processing.org/topic/manipulating-sentences-please-help
    I prefer to avoid redundancy and multiple identical threads, so I deleted this one too.

    Now, let's focus on the new thread.