1. Introduction
Analyzing textual data often requires looking for specific patterns or words. For instance, understanding how often a certain word appears can be pivotal for sentiment analysis, SEO optimizations, or academic research. This guide illustrates how to create a Ruby program to count the occurrences of a specific word in a file.
2. Program Steps
1. Specify the path of the file you want to check.
2. Define the word you want to search for.
3. Open the file in reading mode.
4. Read the file's content line by line.
5. For each line, count occurrences of the specified word.
6. Accumulate the count for each line.
7. Display the total occurrences of the word.
3. Code Program
# Specify the path of the file you want to check
file_path = "sample_file.txt"
# Specify the word you want to search for
target_word = "Ruby"
# Initialize a counter for the occurrences
occurrences = 0
# Open and read the file
File.open(file_path, "r") do |file|
file.each_line do |line|
# Count occurrences of the target word in the line
occurrences += line.scan(target_word).size
end
end
# Print the occurrences
puts "The word '#{target_word}' occurred #{occurrences} times in the file #{file_path}."
Output:
The word 'Ruby' occurred 25 times in the file sample_file.txt.
Explanation:
1. file_path = "sample_file.txt": This line designates the path or name of the file you intend to inspect.
2. target_word = "Ruby": The word you're interested in counting its occurrences.
3. File.open(file_path, "r") do |file|: The open method from the File class opens the specified file in reading mode.
4. file.each_line do |line|: This iterates through each line of the file.
5. occurrences += line.scan(target_word).size: The scan method searches for all occurrences of the target_word in a line. We then determine the size of the resulting array, which represents the count of occurrences in that line.
6. puts "The word '#{target_word}' occurred #{occurrences} times in the file #{file_path}.": We display the total occurrences of the specified word.
Comments
Post a Comment