i have 3 paragraphs and i try to get one sentence per paragraph. but, the sentences taken randomly.
beside that, it performed a total of 2 times iteration.
example :
String sentences = "i love u. i like u. i get money. \nOther side.
A new car. white paint. \nSomething else. i see the sky.
i took a money yesterday. ";
there are 3 paragraphs and 9 sentences. I want to get output like this :
output :
(P : Paragraph, S = Sentence)
First iteration :
P0S1 : i like you
P1S0 : Other side
P2S1 : i see the sky
second iteration :
P0S2 : i get money
P1S2 : white paint
P2S0 : Something else
the sentence above is get by randomly
i have tried to pair the key and its sentence, but don't how to get the sentence randomly
my code :
Map<String,String> mapIndeksKeyAndSentence = new LinkedHashMap<String,String>();
String sentences = "i love u. i like u. i get money. \nOther side.
A new car. white paint. \nSomething else. i see the sky.
i took a money yesterday. ";
String [] arrSentence = sentence.split("\n");
for(int i=0; i<arrSentence.length; i++){
String[] arrSentenceByDot = arrSentence[i].split("\\. ");
for(int j=0; j<arrSentenceByDot.length; j++){
mapIndeksKeyAndSentence.put(i+""+j, arrSentenceByDot[j]);
}
}
and the ouput of mapIndeksKeyAndSentence is ::
the index : 00 //means = paragraph one, sentence one
the sentence : i love you
.
.
.
etc . .
so, how do i get the sentence randomly with two iterations?.. help, please.
You could make a list of all possible indices and suffle it using Collections.suffle(...). Something like this:
import java.util.Collections;
...
...
List<Integer> indices = new ArrayList<>(arrSentenceByDot.length);
for(int j=0; j<arrSentenceByDot.length; j++){
indices.add(j);
}
Collections.shuffle(indices);
for(int j=0; j<indices.size(); j++){
int index = indices.get(j);
mapIndeksKeyAndSentence.put(i+""+index, arrSentenceByDot[index]);
}
try:
public static void main(String[] args) {
String sentences = "i love u. i like u. i get money. \nOther side. A new car. white paint. \nSomething else. i see the sky. i took a money yesterday. ";
List<String[]> paragraphs = new ArrayList<String[]>();
for(String s : sentences.split("\n"))
paragraphs.add(s.split("\\. "));
int i = 0;
for(String[] ss : paragraphs)
System.out.println("P" + i++ + "S" + getRandom(ss));
}
public static String getRandom(String[] s) {
int i = (int) (Math.random() * s.length);
return s[i];
}
Related
I've been trying for a while now, and I just give up. I want to extract the data from type (regardless whether it's a capital letter or not) to the numbers. Pretty much, I'm trying to get rid of model and birthday in each line, but what makes it even more difficult, is that it's all one string. I spaced it out just to make it easier to read.
I'm trying to find the answer in REGEX java. This is what I was trying but, is deleting of course the whole String after the first number(4,66)
[;][mo].*
Thank you in advance!
Input:
Type:Carro;high:4,66;model:fourDoors;birthday:01/01/1980
type:Truck;high:5,66;model:twoDoors;birthday:29/05/1977
tYpe:motorcycle;high:1,55;model:fiveDoors;birthday:01/01/1980
type:Carro;high:4,66;type:model;birthday:6/12/1887
type:Carro;high:9,66;model:Doors;birthday:05/12/2010
Expected OutPut:
Type:Carro;high:4,66
type:Truck;high:5,66
tYpe:motorcycle;high:1,55
type:Carro;high:4,66
type:Carro;high:9,66
Hopefully this will work for you. There are a few ways to make this code slightly smaller, however, this should at least help to get you on the right path.
I placed it into a main method, but it would be easy to put it into its own function. This would allow you to pass any number of arrays at it.
I added all of the logic in the comments within the code, I hope it helps:
public static void main(String[] args) {
/*Get your strings into an Array*/
String[] str = {"Type:Carro;high:4,66;model:fourDoors;birthday:01/01/1980",
"type:Truck;high:5,66;model:twoDoors;birthday:29/05/1977",
"tYpe:motorcycle;high:1,55;model:fiveDoors;birthday:01/01/1980",
"type:Carro;high:4,66;type:model;birthday:6/12/1887",
"type:Carro;high:9,66;model:Doors;birthday:05/12/2010",
"Expected OutPut:",
"Type:Carro;high:4,66",
"type:Truck;high:5,66",
"tYpe:motorcycle;high:1,55",
"type:Carro;high:4,66",
"type:Carro;high:9,66"
};
/*Create a "final staging" array*/
String[] newStr = new String[str.length - 1];
for (int j = 0; j < str.length - 1; j++) {//For each of your strings
str[j] = str[j].toLowerCase();//set the string to lower
/*If they don't contain a semi-colon and a model or birthday reference go to else*/
if (str[j].contains(";") && str[j].contains("model") || str[j].contains("birthday")) {
/*Otherwise, split the string by semi-colon*/
String[] sParts = str[j].split(";");
String newString = "";//the new string that will be created
for (int i = 0; i < sParts.length - 1; i++) {//for each part of the sParts array
if (sParts[i].contains("model") || sParts[i].contains("birthday")) {//if it contains what is not desired
//Do Nothing
} else {
newString += sParts[i];//otherwise concatenate it to the newString
}
newStr[j] = newString;//add the string to the "final staging" array
}
} else {
newStr[j] = str[j];//if it didn't have semi-colons and birthday or model, just add it to the "final staging" array
}
}
for (String newS : newStr) {// finally if you want to see the "final staging" array data... output it.
System.out.println(newS);
}
}
OUTPUT
type:carrohigh:4,66
type:truckhigh:5,66
type:motorcyclehigh:1,55
type:carrohigh:4,66
type:carrohigh:9,66
expected output:
type:carro;high:4,66
type:truck;high:5,66
type:motorcycle;high:1,55
type:carro;high:4,66
If I happened to miss something in the requirements, please let me know, I would be happy to fix it.
String str = "Type:Carro;high:4,66;model:fourDoors;birthday:01/01/1980,type:Truck;high:5,66;model:twoDoors;birthday:29/05/1977,tYpe:motorcycle;high:1,55;model:fiveDoors;birthday:01/01/1980,type:Carro;high:4,66;type:model;birthday:6/12/1887";
StringTokenizer tokens = new StringTokenizer(str, ",");
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken() ;
StringTokenizer tokens2 = new StringTokenizer(token, ":");
while (tokens2.hasMoreTokens()) {
String key = tokens2.nextToken() ;
if (key.equalsIgnoreCase("type")){
System.out.println("locate: "+key+"\n");
}
}
}
I am trying to see if a ArrayList of strings contains a word located in another string , but i am doing something wrong. Here is my code:
Here is an example of my ArrayList
titles = {"Sodium " , " Lithium " , "Allura Red AC"};
String ocrRes = "I want some sugar , and some coffee with Allura Red AC , Ponceau 4R ";
for (int i = 0; i < titles.size() ; i++)
{
if (ocrRes.contains(titles.get(i)) )
{
ocrResult.setText(titles.get(i));
}
}
Any help will be much appreciated. Thank you in advance.
Here is an outline of how you would find a specific word in a string array:
String[] array;
//will return the index of the array where word found.
int checkWord(String searchWord)
{
for(int i = 0; i < array.length; i++)
{
if (searchWord.equals(array[i]))
return i;
}
}
You could implement something like this to find a word in your array, hope this helps :)
Your'e code seems to work fine...
you probably didn't use the ArrayList as u should
use like this:
List<String> titles = new ArrayList<>();
titles.add("Sodium");
titles.add("Lithium");
titles.add("Allura Red AC");
String ocrRes = "I want some sugar , and some coffee with Allura Red AC , Ponceau 4R ";
for (int i = 0; i < titles.size() ; i++)
{
if (ocrRes.contains(titles.get(i)) )
{
ocrResult.setText(titles.get(i));
}
}
Edit:
Iv'e seen on your comments to other answeres u need another list with corresponding indexes so just create an array list the same why as I showed u in the code above...
Btw the the way u seem to init your list is like your initing an array
which is different type and looks like this:
String[] array = {"Sodium " , " Lithium " , "Allura Red AC"};
gl
Here's another option using ListIterator
String ocrRes = "I want some sugar , and some coffee with Allura Red AC , Ponceau 4R ";
List<String> titles = Arrays.asList("Sodium", "Lithium", "Allura Red AC");
ListIterator<String> iterator = titles.listIterator();
while (iterator.hasNext()) {
String title = iterator.next();
if(ocrRes.contains(title)) {
System.out.println(title);
}
}
You can try this one. If a ArrayList of strings contains a word located in another String. It will display the that String only.
Sample Code
String str = "I want some sugar , and some coffee with Allura Red AC , Ponceau 4R ";
List<String> myList = Arrays.asList("Sodium", "Lithium", "Allura Red AC");
myList.forEach(new Consumer<String>() {
public void accept(String s) {
if(str.contains(s)) {
System.out.println(s);
}
}
});
I am new to java . I have this String.
str="plane,cat,red,dogy";
I want to make a loop and send the data . the below is wrong but i want something similar to it.
for ( int i = 0; i>str.length; i++)
{
str=split.string(,);
// i know it wrong but I want to get the result before comma, for example first loop plane, second loop cat third loop red and so on
updatestatement(str);
}
This should be what you are looking for:
String str="plane,cat,red,dogy";
for(String subString: str.split(",")){
updatestatement(subString);
}
String[] words= str.split(",");
for (String w : words){
//Do whatever you want with each word
}
Don't use for to split. Just:
String[] parts = str.split(",");
It is very unclear what you need. But i think you are looking for this:
String[] s = str.split(",");
for ( int i = 0; i<s.length; i++)
{
// i know it wrong but I want to get the result before comma, for example first loop plane, second loop cat third loop red and so on
updatestatement(str);
}
Where updatestatement is a method in your class
The answer is simple.
String str="plane,cat,red,dogy";
String[] items = str.split(",");
System.out.println("No of items::"+items.length);
If you want to print each item,
for (String eachItem : items) {
System.out.println(eachItem);
//updateStatement(eachItem);
}
You should do it as follows :
String str="plane,cat,red,dogy";
String[]str1=str.split(",");
for ( int i = 0; i>str1.length; i++)
{
updatestatement(str1[i]);
}
String str="plane,cat,red,dogy";
String[] parts = str.split(",");
Arrays.stream(parts).forEach(System.out::println);
This solution only works with Java 8 because of the stream method. If you remove the last line it also works with other Java versions.
I just beginning to learn java, so please don't mind.
I have string
String test="John Software_Engineer Kartika QA Xing Project_Manager Mark CEO Celina Assistant_Developer";
I want to splitting based of position of Company={"Software_Engineer", "QA","Project_Manager","CEO ","Assistant_Developer"};
EDITED:
if above is difficulties then is it possible??? Based or {AND, OR)
String value="NA_USA >= 15 AND NA_USA=< 30 OR NA_USA!=80"
String value1="EUROPE_SPAIN >= 5 OR EUROPE_SPAIN < = 30 "
How to split and put in hashtable in java. finally how to access it from the end. this is not necessary but my main concern is how to split.
Next EDIT:
I got solution from this, it is the best idea or not????
String to="USA AND JAPAN OR SPAIN AND CHINA";
String [] ind= new String[]{"AND", "OR"};
for (int hj = 0; hj < ind.length; hj++){
to=to.replaceAll(ind[hj].toString(), "*");
}
System.out.println(" (=to=) "+to);
String[] partsparts = to.split("\\*");
for (int hj1 = 0; hj1 < partsparts.length; hj1++){
System.out.println(" (=partsparts=) "+partsparts[hj1].toString());
}
and
List<String> test1=split(to, '*', 1);
System.out.println("-str333->"+test1);
New EDIT:
If I have this type of String how can you splitting:
final String PLAYER = "IF John END IF Football(soccer) END IF Abdul-Jabbar tennis player END IF Karim -1996 * 1974 END IF";
How can i get like this: String [] data=[John , Football(soccer) ,Abdul-Jabbar tennis player, Karim -1996 * 1974 ]
Do you have any idea???
This will split your string for you and store it in a string array(Max size 50).
private static String[]split = new String[50];
public static void main(String[] args) {
String test="John -Software_Engineer Kartika -QA Xing -Project_Manager Mark -CEO Celina -Assistant_Developer";
for (String retval: test.split("-")){
int i = 0;
split[i]=retval;
System.out.println(split[i]);
i++;
}
}
You can make a string with Name:post and space. then it will be easy get desire value.
String test="John:Software_Engineer Kartika:QA Xing:Project_Manager"
I am unable to comment as my reputation is less. Hence i am writing over here.
Your first Question of String splitting could be generalized as positional word splitting. If it is guaranteed that you require all even positioned string, you could first split the string based on the space and pull all the even position string.
On your Second Question on AND & OR split, you could replace all " AND " & " OR " with single String " " and you could split the output string by single space string " ".
On your third Question, replace "IF " & " END" with single space string " " and I am not sure whether last IF do occurs in your string. If so you could replace it too with empty string "" and then split the string based on single space string " ".
First classify your input string based on patterns and please devise an algorithm before you work on Java.
I would suggest you to use StringBuffer or StringBuilder instead of using String directly as the cost is high for String Operation when compared to the above to.
try this
String[] a = test.replaceAll("\\w+ (\\w+)", "$1").split(" ");
here we first replace word pairs with the second word, then split by space
You can take a set which have all positions Like
Set<String> positions = new HashSet<String>();
positions.add("Software_Engineer");
positions.add("QA");
String test="John Software_Engineer Kartika QA Xing Project_Manager Mark CEO Celina Assistant_Developer";
List<String> positionsInString = new ArrayList<String>();
Iterator<String> iterator = positions.iterator();
while (iterator.hasNext()) {
String position = (String) iterator.next();
if(test.contains(position)){
positionsInString.add(position);
break;
}
}
I am trying to find and print the words in a string that occurs more than one. And it works almost. I am however fighting with a small problem. The words a printed out twice since they occur twice in the sentence. I want them printed only once:
This is my code:
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String sentence = "is this a sentence or is this not ";
String[] myStringArray = sentence.split(" "); //Split the sentence by space.
int[] count = new int[myStringArray.length];
for (int i = 0; i < myStringArray.length; i++){
for (int j = 0; j < myStringArray.length; j++){
if (myStringArray[i].matches(myStringArray[j]))
count[i]++;
//else break;
}
}
for (int i = 0; i < myStringArray.length; i++) {
if (count[i] > 1)
System.out.println("1b. - Tokens that occurs more than once: " + myStringArray[i] + "\n");
}
}
}
You can try for (int i = 0; i < myStringArray.length; i+=2) instead.
break on the first match, after incrementing. then it won't also increment the second match.
Your code has some problems with it.
If you notice, your code will look through the list of n elements n^2 times.
If the occurrence of the word is twice. You will increment each word's count value twice.
What you need to keep track of is the set of words you have already seen, and check if a new word you encounter has already been seen or not.
If you had 3 occurrence of one word in your sentence, you each word would have a count of 3. The 3 is redundant data that doesn't need to be stored for each token, but rather just the word.
All this can be done easily if you know how a Map works.
Here is an implementation that would work.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
String sentence = "is this a sentence or is this not ";
String[] myStringArray = sentence.split("\\s"); //Split the sentence by space.
Map <String, Integer> wordOccurrences = new HashMap <String, Integer> (myStringArray.length);
for (String word : myStringArray)
if (wordOccurrences.contains(word))
wordOccurrences.put(word, wordOccurrences.get(word) + 1);
else wordOccurrences.put(word, 1);
for (String word : wordOccurrences.keySet())
if (wordOccurrences.get(word) > 1)
System.out.println("1b. - Tokens that occurs more than once: " + word + "\n");
}
}
We want to find the repeating words from an input string. So, I suggest the following approach which is fairly simple:
Make a Hash Map instance. The key (String) will be the word and the value(Integer) will be the frequency of its occurrence.
Split the string using split("\s") method to make an array of only words.
Introduce an Integer type 'frequency' variable with initial value '0'.
Iterate of the string array and after checking frequency, add each element ( or word) to the map (if frequency for that key is 0) or if
the key (word) exists, only increment the frequency by 1.
So you are now left with each word and its frequency.
For example, if input string is "We are getting dirty as this earth is getting polluted. We must stop it."
So, the map will be
{ ("We",2), ("are",1), ("getting",2), ("dirty",1), ("as",1), ("this",1), ("earth",1), ("is",1), ("polluted.",1), ("must",1), ("stop",1), ("it.",1) }
Now you know what is next step and how to use it. I agree with Kaushik.