gpt4 book ai didi

java - 使用java分割它

转载 作者:行者123 更新时间:2023-11-30 05:09:09 25 4
gpt4 key购买 nike

我需要分割并串起来

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

这应该写为

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

我如何使用java来做到这一点

已编辑

文件表达式.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());




}

}

并尝试告诉我我仍然收到错误

最佳答案

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...您需要处理这种情况。

关于java - 使用java分割它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4071394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com