【问题标题】:How do I process each five words in a text file in Java?如何在 Java 中处理文本文件中的每五个单词?
【发布时间】:2011-04-06 04:53:11
【问题描述】:

大家好;

我有一个文本文件说“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,do functions...等直到文件结束。

我想用 java.Any Ideas 做到这一点?

【问题讨论】:

  • 到目前为止你有什么?

标签: java text-files


【解决方案1】:

所以这个伪代码:

  • 读取文件
  • 将单词放入列表中
  • 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 );
  }
}

【讨论】:

  • 你不应该在process (five);之后的else块中调用five.removeAll ()吗?
  • 谢谢你的回复,但是你能澄清一下你的代码吗?
  • @user 未知:确实!... @Daisy,几乎没有。我认为这已经很清楚了,因为我并不是要为你做你的工作。您必须向我们展示您到目前为止所拥有的东西以及您需要帮助的什么。这不是做我的功课网站。对不起
  • 我知道这不是“做我的家庭作业网站”。感谢您的友好回复。
【解决方案2】:

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

【讨论】:

  • 感谢您的回复。我如何实现它以循环每组 5 个单词。
  • while 将循环每个匹配的组。每组将从工作字符串中切出一串 5 个单词。如果您需要然后循环 5 个分组单词的字符串,您可以在空格处拆分。
【解决方案3】:

查看 SDK 中的 String.split() 方法。可能会为您指明前进的方向。

【讨论】:

    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      相关资源
      最近更新 更多