【问题标题】:Storing each sentence in an array from a document in java?将Java文档中的每个句子存储在数组中?
【发布时间】:2014-04-06 14:10:45
【问题描述】:

我想从文档中拆分每个句子并将每个句子存储在不同的数组中。每个数组元素是 句子的词。但我不能远离这一点。

int count =0,len=0;
String sentence[];
String words[][];
sentence = name.split("\\.");
count = sentence.length;

System.out.print("total sentence: " );
System.out.println(count);
int h;  
words = new String[count][]; 

for (h = 0; h < count; h++) {
     String tmp[] = sentence[h].split(" ");
     words[h] = tmp;
     len = len + words[h].length;
     System.out.println("total words: " );
     System.out.print(len); 

     temp = sentence[h].split(delimiter);  

     for(int i = 0; i < temp.length; i++) {
        System.out.print(len);
        System.out.println(temp[i]);
        len++;
     }  
}

【问题讨论】:

  • 这段代码没问题。我不知道如何在数组中存储单词。我确实将每个单词从句子中分开。但是我怎样才能将它们存储在数组中?
  • 当你使用split 方法时,它会给你一个数组作为结果,不需要创建一个。
  • 哦!但我怎样才能看到或访问数组?我需要使用数组进行进一步计算。
  • 如果您执行words[] = someString.split(" ") 之类的操作,则数组words 包含围绕空格分割的所有元素。现在您可以访问这些元素,例如words[0]words[1] 等...
  • 还有什么不工作的地方吗?

标签: java arrays words sentence


【解决方案1】:

我无法理解您的代码,但以下是如何通过 3 行代码实现您的声明意图:

String document; // read from somewhere

List<List<String>> words = new ArrayList<>();
for (String sentence : document.split("[.?!]\\s*"))
    words.add(Arrays.asList(sentence.split("[ ,;:]+")));

如果要将Lists 转换为数组,请使用List.asArray(),但我不建议这样做。列表比数组更容易处理。一方面,它们会自动扩展(上述代码如此密集的原因之一)。

附录:(大多数)字符不需要在字符类中转义。

【讨论】:

  • 显示此错误 - 列表无法解析为类型。列表无法解析为类型。 ArrayList 无法解析为类型。标记“
  • @user3503711 你需要import java.util.*;。如果您使用的是 java 6,请改用 new ArrayList&lt;List&lt;String&gt;&gt;()
【解决方案2】:

您的输入字符串似乎存储在main 中。 我不明白内部for 循环应该做什么:它反复打印len,但不更新它!

String sentences[];
String words[][];

// End punctuation marks are ['.', '?', '!']
sentences = name.split("[\\.\\?\\!]"); 

System.out.println("num of sentences: " + sentences.length);

// Allocate stogage for (sentences.length) new arrays of strings
words = new String[sentences.length][];

// For each sentence
for (int h = 0; h < sentences.length; h++) {
  // Remove spaces from beginning and end of sentence (to avoid 0-length words)
  // split by any white space character sequence (caution if using Unicode!)
  words[h] = sentences[h].trim().split("\\s+"); 

  // Print out length of sentence.
  System.out.println("words (in sentence " + (h+1) + "): " + words[h].length);
}

【讨论】:

  • 实际长度只是为了看看代码是否有效!我需要的是>> 输入-我吃米饭。他是个男孩。输出如 -array[1]={i,eat,rice} 。数组[2]={he,is,a,boy}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多