2017-08-30 55 views
-2

我有一個這樣的輸入在文本文件中 例如:匹配詞,並強調它

輸入文件1:「店在週日開放」

輸入文件2:「每週五,折扣將是」

輸入文件3:「在本週星期一開始」

我想建的天名的文件,這樣 文件的話:

  • 週六
  • 週日
  • 週一
  • 週二
  • 週三
  • 週四
  • 週五

你能幫助我的代碼在文本文件中日 亮點名文字在Java代碼中

+2

你試過了什麼,向我們展示一些代碼和你面臨的問題? –

+0

輸入中是否只包含一個天的名字? – HAYMbl4

回答

0

這是一件容易的事,我想匹配的一天名稱。我們需要一個包含天數名稱的列表。然後逐字閱讀文件並檢查列表是否包含該單詞。如果列表包含單詞,那麼它是必需的,我們將把它放到輸出文件中。 我在這裏貼上我的代碼,請讓我知道如果你想別的東西:

import java.io.File; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.util.Arrays; 
import java.util.List; 
import java.util.Scanner; 

public class Prgo2 { 
    public static void main(String[] args) throws IOException { 
     String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; 
     List<String> daysList = Arrays.asList(days); 
     // We can create direct list also 
     Scanner sc = new Scanner(new File("C:\\vishal\\abc.txt")); 
     FileWriter wr = new FileWriter(new File("C:\\vishal\\days.txt")); 

     while (sc.hasNext()) { 
      String s = sc.next(); 
      if (daysList.contains(s)){ 
       wr.write(s); 
      } 

     } 
     wr.close(); 
    } 
} 
0

您可以使用正則表達式expresion解析的文件名。我寫了兩個方法一個返回List創建日期名稱和其他返回只有一個值。

public class Test { 

    private static final String file1 = "opening of the shop on sunday"; 
    private static final String file2 = "Every friday , the discount will be "; 
    private static final String file3 = "start in the week on monday "; 
    private static final String fileWithSeveralDays = "monday start in the week on monday and every thursday"; 

    private static final Pattern pattern = Pattern 
      .compile("(saturday|sunday|monday|tuesday|wednesday|thursday|friday)"); 

    public static void main(String[] args) { 
     Map<String, Set<String>> fileToDaysMap = new HashMap<>(); 

     fileToDaysMap.put(file1, findAllMatches(file1)); 
     fileToDaysMap.put(file2, findAllMatches(file2)); 
     fileToDaysMap.put(file3, findAllMatches(file3)); 
     fileToDaysMap.put(fileWithSeveralDays, findAllMatches(fileWithSeveralDays)); 

     String singleDay = findSingleOrNull(file1); 
    } 

    private static Set<String> findAllMatches(String fileName) { 
     Set<String> matches = new HashSet<>(); 
     Matcher matcher = pattern.matcher(fileName); 
     while (matcher.find()) { 
      matches.add(matcher.group(1)); 
     } 
     return matches; 
    } 

    private static String findSingleOrNull(String fileName) { 
     Matcher matcher = pattern.matcher(fileName); 
     return matcher.find() ? matcher.group(1) : null; 
    } 

}