2011-04-05 32 views
1

問候所有;如何處理Java中的文本文件中的每個五個單詞?

我有一個文本文件說「test.txt」,我只想對每5個字進行處理。

例如,如果中的test.txt包含:

On the Insert tab the galleries include items that are designed to coordinate with the overall look of your document.

我想拿第一五個字:On the Insert tab the,做他們的一些功能。然後接下來的五個詞galleries include items that are,做功能等等,直到文件結束。

我想用java.Any Ideas做到這一點?

+1

你有什麼這麼遠嗎? – OscarRyz 2011-04-05 20:03:14

回答

0

5個單詞組,然後遍歷找到的匹配項。

Pattern p = Pattern.compile("(\\w*\\s?){5}"); 
String s = "On the Insert tab the galleries include items that are designed to coordinate with the overall look of your document."; 
Matcher m = p.matcher(s); 
while (m.find()) { 
    String words_group = m.group(); 
    System.out.println(words_group); 
} 

要拆分的words_group您可以:

words_group.split(" "); // returns String[] 
+0

謝謝您的回覆。我如何實現它以循環每組5個單詞。 – Daisy 2011-04-05 20:36:12

+0

'while'會循環每個匹配的組。每個組將從工作字符串切下一串5個字。如果你需要循環5個分組字符串,你可以分割空白。 – 2011-04-05 20:40:46

+0

謝謝你的幫助。 – Daisy 2011-04-05 21:03:19

1

所以這個僞代碼:

  • 讀取文件
  • 把話說在列表
  • 同時(還未經處理項目)
    • 以後以五
    • processThem
  • 重複

可以沿着路線實施。

String fileContent = readFile("test.txt"); 
List<String> words = splitWordsIntoList(fileContent); 
int n = 0; 
List<String> five = new ArrayList<String>(); 
for(String word : words) { 
    if(n++ < 5) { 
    five.add(word); 
    } else { 
     n = 0 ; 
     process(five); 
    } 
} 
+1

不應該在'process(5);'之後的else塊中調用'five.removeAll()'? – 2011-04-05 20:29:39

+0

感謝您的回覆,但您是否會澄清一下您的代碼。 – Daisy 2011-04-05 20:31:59

+0

@用戶未知:確實!... @Daisy,幾乎沒有。我認爲這很清楚,因爲我沒有試圖爲你做你的工作。你必須告訴我們你到目前爲止所做的事情,以及**你需要幫助的事情。這不是*做我的家庭作業*網站。對不起 – OscarRyz 2011-04-05 20:41:27

0

查看SDK中的String.split()方法。可能會讓你成爲你前進的好方法。

0

您可以將整個文本文件讀入單個字符串,並且只要您感興趣的單詞總是用空格分隔,就可以使用字符串標記器來創建單詞數組。

相關問題