2013-10-16 35 views
1

我已经从“web 2.0维基百科”文章中提取文本,并将其拆分为“句子”。之后,我将创建“字符串”,每个字符串包含5个句子。问题在组合拆分字符串

当提取,文字看起来像下面,在EditText

enter image description here

下面是我的代码

finalText = textField.getText().toString(); 

String[] textArrayWithFullStop = finalText.split("\\. "); 
String colelctionOfFiveSentences = ""; 

List<String>textCollection = new ArrayList<String>(); 
for(int i=0;i<textArrayWithFullStop.length;i++) 
{ 
    colelctionOfFiveSentences = colelctionOfFiveSentences +  textArrayWithFullStop[i]; 
    if((i%5==0)) 
    { 
     textCollection.add(colelctionOfFiveSentences); 
     colelctionOfFiveSentences = ""; 
    } 
} 

但是,当我使用Toast显示文本,这里是什么给出

Toast.makeText(Talk.this, textCollection.get(0), Toast.LENGTH_LONG).show(); 

enter image description here

正如你所看到的,这只是一句话!但我预计它会有5个句子!

另一件事是,第二句是从别的地方开始。在这里我怎么解压缩成Toast

Toast.makeText(Talk.this, textCollection.get(1), Toast.LENGTH_LONG).show(); 

enter image description here

这是没有意义的我!我该如何正确地将文本拆分成句子,并创建包含5个句子的Strings?请帮助

+1

正如你所看到的,并不是所有的句子以期间和空间结束。一些与一些资源链接的端点,例如[1] – Admit

+0

@Admit:是的,我也需要为此找到解决方案。 –

回答

2

的问题是,第一句,0%5 = 0,所以它被立即添加到数组列表。你应该使用另一个计数器而不是mod。

finalText = textField.getText().toString(); 

String[] textArrayWithFullStop = finalText.split("\\. "); 
String colelctionOfFiveSentences = ""; 
int sentenceAdded = 0; 

List<String>textCollection = new ArrayList<String>(); 
for(int i=0;i<textArrayWithFullStop.length;i++) 
{ 
    colelctionOfFiveSentences += textArrayWithFullStop[i] + ". "; 
    sentenceAdded++; 
    if(sentenceAdded == 5) 
    { 
     textCollection.add(colelctionOfFiveSentences); 
     colelctionOfFiveSentences = ""; 
     sentenceAdded = 0; 
    } 
} 
+1

OP也可以用'i = 1'开始循环并添加'colelctionOfFiveSentences + = textArrayWithFullStop [i-1] +“。”;'。或者如果OP希望以'i = 0'开始,则条件变成'if(i%5 == 4)'。恕我直言,不需要添加计数器。 –

+0

太好了。谢谢! –

2

添加". "textArrayWithFullStop[i]

colelctionOfFiveSentences = colelctionOfFiveSentences + textArrayWithFullStop[i]+". "; 
+0

非常感谢你的回复。对此,我真的非常感激。从我+1。 :) –

2

我相信,如果你修改国防部线这样的:

if(i%5==4) 

,你将有你需要的东西。

你可能认识到这一点,但也有为什么有人可能会使用其他原因“”,实际上并没有结束一个句子,例如

I spoke to John and he said... "I went to the store. 
Then I went to the Tennis courts.", 
and I don't believe he was telling the truth because 
1. Why would someone go to play tennis after going to the store and 
2. John has no legs! 
I had to ask, am I going to let him get away with these lies? 

那两句话不结束一段时间,并会误导你的代码,认为它是在完全错误的地方分解了5个句子,所以这种方法确实充满了问题。但是,作为分割字符串的练习,我想它和其他的一样好。

+0

非常感谢您的回复。对此,我真的非常感激。从我+1。 :) –

1

作为一个方面的问题(分裂句)解决方案,我建议先从这个正则表达式

string.split(".(\\[[0-9\\[\\]]+\\])? ") 

而对于主要的问题可能是,你可以使用copyOfRange()

+0

非常感谢你的回复。对此,我真的非常感激。从我+1。 :) –