简体   繁体   中英

How do I process each five words in a text file in Java?

Greetings All;

I have a text file say "test.txt" and I want to make process on each 5 words only.

for example if the test.txt contain:

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

I want to take the first five words: On the Insert tab the , do some functions on them. then the next five words galleries include items that are ,do functions...etc until the end of the file.

I want to do that with java.Any Ideas?

So this pseudo code:

  • Read the file
  • Put the words in a list
  • while( remain unprocessed items )
    • Take five
    • processThem
  • repeat

Could be implemented along the lines.

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 );
  }
}

Check out the String.split() method in the SDK. Probably gets you a good ways where you're heading.

您可以将整个文本文件读取为单个字符串,并使用字符串标记器创建单词数组,只要您感兴趣的单词始终用空格分隔即可。

Word groups of 5, then loop over the found matches.

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);
}

To split the words_group you can:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM