我正在構建一個android/Java程序,它從文本文件中讀取並將每個句子存儲在數組列表中的文本文件中。然後它檢查句子中每個單詞的出現並打印出包含重複單詞的所有句子。LinkedHashSet無法從ArrayList刪除重複的句子
這是我使用打印出來的最終結果代碼:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text4);
text = (TextView)findViewById(R.id.info2);
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("input3.txt")));
String line;
List<String> sentences = new ArrayList<String>();
for (String line2; (line2 = reader.readLine()) != null;) {
for (String sentence : line2.split("(?<=[.?!\t])")) {
sentence = sentence.trim();
if (! sentence.isEmpty()) {
sentences.add(sentence);
}
}
String[] keys = line2.split(" ");
String[] uniqueKeys;
int count = 0;
uniqueKeys = getUniqueKeys(keys);
for(String key: uniqueKeys)
{
if(null == key)
{
break;
}
for(String s : keys)
{
if(key.equals(s))
{
count++;
}
}
if(key.equals("a") || key.equals("the")|| key.equals("is")|| key.equals("of")|| key.equals("and")|| key.equals("The") || key.equals("some") || key.equals("on") || key.equals("during") || key.equals("to") || key.equals("since") || key.equals("in") || key.equals("by") || key.equals("for") || key.equals("were") ||key.equals("--") || key.equals("in") || key.equals("as") || key.equals("that") || key.equals("may") || key.equals("can") || key.equals("without") || key.equals("You")){
count = 0;
}
if(count >1){
MyKey = key;
Pattern word = Pattern.compile("\\b"+key+"\\b", Pattern.CASE_INSENSITIVE);
//sentences is the arrayList of sentences in this program
LinkedHashSet<String> lhs = new LinkedHashSet<String>();
for (String sentence : sentences) {
//checks the occurance of keyword within each sentence
if (word.matcher(sentence).find()) {
lhs.add(sentence);
}
}
for (String sentence2 : lhs) {
text.append(sentence2);
}
}
count=0;
}
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
}
我的程序首先讀取一個文本文件,然後在我的文本文件中的每個句子存儲在句子的ArrayList稱爲「句子」。
然後讀取文本文件中的每個詞,它存儲了每一個被重複多次在所謂的「鑰匙」的ArrayList字。
然後檢查的「鑰匙」無論是在每個句子存在,如果是這樣,它增加了這些句子變成所謂的「LHS」的LinkedHashSet。
那麼就應該顯示在輸出屏幕上LinkedHashSet的所有句子。
在此之際,我的「鑰匙」的值是「速度」,「國家」和「政府」
然而,我的文本文件包含了這樣一句話:「十三州報告上方的失業率目前的全國率。「
正如你所看到的,它同時包含「國家」和「速度」,這是我的兩個關鍵詞。
當我運行這個程序,這個特別的句子出現兩次在輸出屏幕上,因爲該程序查找每一個「關鍵」分開,因此認爲它們是兩個不同的句子。
這就是爲什麼我用LinkedHashSet來防止這一點,但它仍然顯示了這句話兩次在輸出屏幕上。
我該如何解決這個問題?
你爲什麼要添加字符串文本= 「」;文本是我的TextView的名稱 – user5679217
避免空指針異常。如果你已經宣佈它..只是刪除我的一個.. 如果它適合你..請..投票! (: – febaisi
你可以請現在檢查它,我已經添加了我的程序中的所有代碼 – user5679217