我在文本文件中有这样的输入 例如:
输入文件1 :“星期天开店”
输入文件2 :“每个星期五,折扣将是”
输入文件3 :“星期一在星期开始”
我想建立天文名称的文件,就像这样 文件字:
您可以帮我编写代码以匹配文本文件中的当天名称 在java代码中突出显示文本中的日期名称
答案 0 :(得分:0)
我认为这是一项简单的任务。我们需要一个包含天数名称的列表。然后逐字阅读文件并检查列表是否包含该单词。如果list包含单词,那么它是必需的,我们将把它放入输出文件中。 我在这里粘贴我的代码,如果你想要别的东西,请告诉我:
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();
}
}
答案 1 :(得分:0)
您可以使用regexp 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;
}
}