繁体   English   中英

如何处理Java文本文件中的每个五个单词?

[英]How do I process each five words in a text file in 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执行功能...等的galleries include items that are直到文件末尾。

我想用java.Any想法吗?

所以这个伪代码:

  • 读取文件
  • 将单词放在列表中
  • while(保留未处理的项目)
    • 拿五
    • 处理他们
  • 重复

可以沿线实施。

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

检出SDK中的String.split()方法。 可能会为您提供前往目的地的好方法。

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

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[]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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