2

我如何将单词连接起来list<String>以恢复它的真实形式作为句子

String sentence = "i get money. i love it. i want to buy. something. ";
String[] arrSent = sentence.split("\\. ");

for(int i=0; i<arrSent.length; i++) {
    String[] words = arrSent[i].split("\\ ");
    for(int j=0; j<words.length; j++ {
        listWord.add(words[j]);
    }
}

输出是:

i
get
money
i
love
it
i
want
to
buy
something

我只是想把它重建成真实的形式(作为句子)

更新!!!

我已经尝试过像你建议的那样。但我发现了一个新的困难方法。

我从列表中删除了一个单词“love”,并添加到新列表“listWord2”中。当我将它重建为句子的真实形式时,.新句子中的内容消失了

这是代码:

String [] arrays2 = listKata2.toArray(new String[listWord2.size()]);
sentence = Arrays.deepToString(arrays2).replaceAll(",", "");
System.out.println("result :  : "+sentence);

输出是:

[i get money i it i want to buy something]

.不见了_

我应该再按空格分开listWord2吗?请建议我

4

3 回答 3

1

唯一真正的答案是,一旦你把所有的单词都弄丢了句子之间的句号,就没有办法把它们找回来——信息永远丢失了,然后就不可能重建原始结构。

您需要弄清楚您希望如何(以及实际上是否)保留该信息。一种方法是保留句子数组,只需用单词列表而不是句子字符串填充它,如下所示:

List<List<String>> sentences = new List<List<String>>();
String[] arrSent = sentence.split("\\. ");
for (int i = 0; i < arrSent.length; i++)
    sentences.add(Arrays.asList(arrSend[i].split("\\ "));

然后你会得到类似的东西

(
   ( "i", "get", "money" ),
   ( "i", "love", "it" ),
   ( "i", "want", "to", "buy" ),
   ( "something" )
)

这很容易看出如何从中重建原始文本。

另一种选择可能是保留扁平的单词列表,但为句子终止的位置添加特殊的占位符 - 例如使用null值。扫描单词的算法应该知道如何处理这些占位符而不会崩溃,而重建句子的算法将使用这些来添加句号:

String[] arrSent = sentence.split("\\. ");

for(int i=0; i<arrSent.length; i++) {
    String[] words = arrSent[i].split("\\ ");
    for(int j=0; j<words.length; j++ {
        listWord.add(words[j]);
    }
    listWord.add(null);
}

// Rebuild
StringBuffer output = new StringBuffer();
for (Iterator<String> it = listWord.iterator(); it.hasNext(); ) {
     String val = it.next();
     String nextword = (output.length() > 0 ? " " : "") + val;
     output.append(val == null ? "." : nextword);
}
于 2014-10-07T07:54:30.320 回答
-1

尝试以下:

String sentence = "i get money. i love it. i want to buy. something. ";
String[] arrSent = sentence.split(" ");
sentence=Arrays.toString(arrSent).replaceAll(",", "");
System.out.println(sentence);

输出 :

[i get money. i love it. i want to buy. something.]

上面是如果你想.在句子中,下面是没有.

String sentence = "i get money. i love it. i want to buy. something. ";
String[] arrSent = sentence.split("\\. ");
sentence=Arrays.toString(arrSent).replaceAll(",", "");
System.out.println(sentence);

输出 :

[i get money i love it i want to buy something]
于 2014-10-07T07:07:41.137 回答
-1

做:

String sentence = "i get money. i love it. i want to buy. something. ";
String[] arrSent = sentence.split("\\. ");

String sentenceRebuild = "";
for(int i=0; i<arrSent.length; i++){
  String[] words = arrSent[i].split("\\ ");

  for(int j=0; j<words.length; j++){
    sentenceRebuild += words[j];
  }
}
于 2014-10-07T07:09:38.973 回答