我如何得到每段一句话(随机句子)

时间:2014-10-14 10:50:57

标签: java string random

我有3段,我试着每段一句话。但是,这些句子是随机的。

除此之外,它总共执行了2次迭代。

示例:

String sentences = "i love u. i like u. i get money. \nOther side. 
A new car. white paint. \nSomething else. i see the sky.
i took a money yesterday. ";

有3段和9句话。我想获得这样的输出:

输出:

(P:段落,S =句子)

第一次迭代:

P0S1 : i like you
P1S0 : Other side
P2S1 : i see the sky

第二次迭代:

P0S2 : i get money
P1S2 : white paint
P2S0 : Something else

上面的句子是随机获得的

我试图配对密钥及其句子,但不知道如何随机获取句子

我的代码:

Map<String,String> mapIndeksKeyAndSentence = new LinkedHashMap<String,String>();

String sentences = "i love u. i like u. i get money. \nOther side. 
A new car. white paint. \nSomething else. i see the sky.
i took a money yesterday. ";

String [] arrSentence = sentence.split("\n");
for(int i=0; i<arrSentence.length; i++){

String[] arrSentenceByDot = arrSentence[i].split("\\. ");
for(int j=0; j<arrSentenceByDot.length; j++){

mapIndeksKeyAndSentence.put(i+""+j, arrSentenceByDot[j]);
}
}

并且mapIndeksKeyAndSentence的输出是::

the index : 00   //means = paragraph one, sentence one 
the sentence : i love you
.
.
.
etc . . 

那么,我如何通过两次迭代随机获得句子?请帮助。

2 个答案:

答案 0 :(得分:0)

您可以列出所有可能的索引,并使用Collections.suffle(...)对其进行填充。像这样:

import java.util.Collections;

...
...

List<Integer> indices = new ArrayList<>(arrSentenceByDot.length);

for(int j=0; j<arrSentenceByDot.length; j++){
    indices.add(j);
}

Collections.shuffle(indices);

for(int j=0; j<indices.size(); j++){
    int index = indices.get(j);
    mapIndeksKeyAndSentence.put(i+""+index, arrSentenceByDot[index]);
}

答案 1 :(得分:0)

尝试:

public static void main(String[] args) {
    String sentences = "i love u. i like u. i get money. \nOther side. A new car. white paint. \nSomething else. i see the sky. i took a money yesterday. ";
    List<String[]> paragraphs = new ArrayList<String[]>();
    for(String s : sentences.split("\n"))
        paragraphs.add(s.split("\\. "));

    int i = 0;
    for(String[] ss : paragraphs) 
        System.out.println("P" + i++ + "S" + getRandom(ss));        
}

public static String getRandom(String[] s) {
    int i = (int) (Math.random() * s.length);
    return s[i];
}