2010-11-01 67 views
1

我需要拆分和字符串拆分它使用Java

Sentence:NounPhrase| VerbPhrase 
    NounPhrase:Art| Noun 
    Sample:the 

这应该写成

Sentence:NounPhrase 
Sentence :VerbPhrase 
NounPhrase:Art 
NounPhrase: Noun 
Sample:the 

我怎么可以这样使用Java

编辑

文件expression.txt

Sentence:NounPhrase VerbPhrase 
NounPhrase:Art Noun 
VerbPhrase:Verb|Adverb Verb 
Art:the|a 
Verb:jumps|sings 
Noun:dog|cat 

节目我用,但不工作

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()); 




    } 

} 

,并试图告诉我易我仍然得到错误

回答

1
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()); 
     } 
    } 
} 

注意:您会遇到ArrayIndexOutOfBoundsException异常,如果你输入的字符串不严格以你提到的格式...你需要照顾这种情况。

+0

不适用于多行 – sundhar 2010-11-01 17:48:22

+0

@ Sundhar..Well ...您需要将您的输入逐行输入到上面的代码片段才能使其正常工作......您如何获得输入?你从文件中读取?或者它是一个单一的字符串? – 2010-11-01 17:51:58

+0

我正在阅读文件 – sundhar 2010-11-01 17:52:37

0

您有3个分隔符line breaks,:|。所以我认为你应该一行一行阅读,然后split两遍。

1

这是一个简单的逻辑:

  • 分割由密钥值中的字符串(隔膜是:K, V对。
  • 从值V|(在v所得)
  • FOREACH V IN V进一步分离它:在列表中添加v。 最后:
  • Map<K, List>中添加v的列表。

希望这会有所帮助。