2013-10-16 32 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。 :) –