簡體   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