2017-08-30 62 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; 
    } 

}