Triển khai một ứng dụng phân tích văn bản
Bạn đang phát triển một ứng dụng phân tích văn bản cần đếm tần suất xuất hiện của các từ trong tài liệu. Bạn cần triển khai một giải pháp có độ phức tạp thời gian tối ưu cho việc tra cứu từ.
Bài tập này là một phần của khóa học
Tối ưu hóa mã trong Java
Hướng dẫn bài tập
- Lấy
currentCountcho từ khi nó đã có trong bản đồ tần suất. - Tăng giá trị đó và cập nhật bản đồ tần suất với giá trị mới.
- Nếu từ chưa có trong bản đồ tần suất cho đến lúc này, hãy thêm nó vào.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
public class Main {
public static void main(String[] args) {
TextAnalyzer analyzer = new TextAnalyzer();
List words = Arrays.asList(
"Java", "is", "a", "programming", "language",
"Java", "is", "widely", "used", "for", "building", "applications",
"Many", "programmers", "use", "Java", "for", "web", "development", "and", "Android", "apps"
);
Map wordFrequency = analyzer.buildWordFrequencyMap(words);
System.out.println("Word frequency analysis:");
for (Map.Entry entry : wordFrequency.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue() + " occurrences");
}
}
}
class TextAnalyzer {
public Map buildWordFrequencyMap(List words) {
Map frequencyMap = new HashMap();
for (String word : words) {
if (word.isEmpty()) {
continue;
}
word = word.toLowerCase();
if (frequencyMap.containsKey(word)) {
// Retrieve the frequency of the word
int currentCount = ____.get(____);
// Increment the frequency of the word
frequencyMap.put(____, currentCount + 1);
} else {
// If the frequency map does not have the word, add it.
____.____(word, 1);
}
}
return frequencyMap;
}
}