2011-04-05 58 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

您可以将整个文本文件读入单个字符串,并且只要您感兴趣的单词总是用空格分隔,就可以使用字符串标记器来创建单词数组。

相关问题