Finden Sie Abkürzungen in der gegebenen Datei mit Java -StreamsJava

Java-Forum
Anonymous
 Finden Sie Abkürzungen in der gegebenen Datei mit Java -Streams

Post by Anonymous »

Eingabe: < /p>
Ein Akronym ist eine Art Abkürzung, die gebildet wird, indem die Ausgangsbuchstaben einer Phrase genommen und ein neues Wort erstellt werden. Akronyme werden oft als Wörter ausgesprochen.

Code: Select all

public class AbbreviationFinderTool {
public static void main(String[] args) {
String filePath = "C:\\MYCODE\\SCPOProjectTool\\INPUT\\aaa.txt"; // Path to your input file

// List of allowed "connector" words in abbreviations
List allowedWords = Arrays.asList("of", "for", "and", "or", "with");

// Regex to match abbreviations allowing connectors and multiple capitalized words
String regex = "([A-Z][a-z]+\\s)*(of|for|and|or|with\\s)*([A-Z][a-z]+\\s?)+";
Pattern pattern = Pattern.compile(regex);

try (Stream lines = Files.lines(Paths.get(filePath))) {
lines.forEach(line -> {
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
String abbreviation = matcher.group().trim();
if (isValidAbbreviation(abbreviation, allowedWords)) {
System.out.println(abbreviation);
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}

// Validates if the extracted phrase is a proper abbreviation
private static boolean isValidAbbreviation(String phrase, List allowedWords) {
String[] words = phrase.split("\\s+");
return Arrays.stream(words).allMatch(word ->
Character.isUpperCase(word.charAt(0)) || allowedWords.contains(word.toLowerCase())
);
}
}
< /code>
Tatsächliche Ausgabe: < /p>
Write
Title
Find
Acronys
Input
An
Acronyms
National Aeronautics
Space Administration
Random Access Memory
Abbreviations
Acronyms
United Nations International Children
Emergency Fund
< /code>
Erwartete Ausgabe: < /p>
National Aeronautics and Space Administration
Random Access Memory
United Nations International Children's Emergency Fund
Bitte helfen Sie mir.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post