Reputation: 845
i need to split and string
Sentence:NounPhrase| VerbPhrase
NounPhrase:Art| Noun
Sample:the
this should be written As
Sentence:NounPhrase
Sentence :VerbPhrase
NounPhrase:Art
NounPhrase: Noun
Sample:the
how can i do this using java
Edited
the file expression.txt
Sentence:NounPhrase VerbPhrase
NounPhrase:Art Noun
VerbPhrase:Verb|Adverb Verb
Art:the|a
Verb:jumps|sings
Noun:dog|cat
the program i used but not working
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
public class shift {
public static String readFileFull(String file)
{
String strLine = null;
StringBuffer sb = new StringBuffer();
try{
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
sb.append("\n");
sb.append(strLine);
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
String ret=sb.toString();
return ret;
}
public static void main(String args[]) {
String speech = readFileFull("c://expression.txt");
StringBuilder sb = new StringBuilder();
Scanner sc = new Scanner(speech);
while (sc.hasNextLine()) {
String[] ps = sc.nextLine().split(":");
for (String s : (ps[1] + "|").split("\\|"))
if (!s.equals(""))
sb.append(ps[0]+":").append(s).append("\n");
}
System.out.println(sb.toString());
}
}
and try to tell me y i am still getting error
Upvotes: 1
Views: 1103
Reputation: 3252
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FileRead {
public static void main(String args[]) {
try {
FileInputStream fstream = new FileInputStream("c:\\expression.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
String a[] = strLine.split(":");
String b[] = a[1].split("\\|");
for (String s1 : b) {
System.out.println(a[0] + ":" + s1.trim());
}
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Note: You will run into ArrayIndexOutOfBoundsException if your input strings do not strict to the format you mentioned...you need to take care of that case.
Upvotes: 1
Reputation: 89189
It's a simple logic of:
:
) K, V
pair.V
separate it further with |
(Resulting in v
)V
: add v
in a list.
Finally:v
's in a Map<K, List>
.Hope this helps.
Upvotes: 1
Reputation: 2254
You have 3 separators line breaks
, :
and |
. so I think you should read line by line then split
twice.
Upvotes: 0