Get Words from a Text File and Sort Them Randomly

Question

I have a text file rext.txt and I'm trying to get first 100 random words from each line of the text file and put them into String array, but it's not working. I figured out how to separate words from text and put them into array, but I couldn’t work out where to include 100 words to get them sorted. Thank you!

 

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Random;

import java.util.Scanner;

 

public class New2

{

public static void main(String[] args) throws FileNotFoundException

{

Scanner sc = new Scanner(new File("dictionary.txt"));

while (sc.hasNext())  

{

String word = sc.next();

sc.nextLine();  

String[] wordArray = word.split(" ");

//System.out.println(Arrays.toString(wordArray));

int idx = new Random().nextInt(wordArray.length);

String random = (wordArray[idx]);

System.out.println(random);

}

}

}

 

Answer

You need to read the text file line by line, split each line into individual words and get the first 100 and arrange them randomly. It’s complicated to hardcode this in Java. But it’s easy to do this in SPL (Structured Process Language) and then embed the SPL script in Java:

A

1

=file("d:\\source.txt").read@n()

2

=A1.(~.words().to(100).sort(rand()))

A1: Read the text file by lines.

A2: Split each line into individual words and get the first 100 words and sort them randomly.

About calling an SPL script in another application, see How to Call an SPL Script in Java.