Answer:
python
Copy code
# Open the text file for reading
with open('text.txt', 'r') as file:
# Initialize an empty dictionary to store word counts
word_counts = {}
# Loop through each line in the file
for line in file:
# Split the line into individual words
words = line.split()
# Loop through each word in the line
for word in words:
# Remove any punctuation from the word
word = word.strip('.,;:?!')
# Convert the word to lowercase
word = word.lower()
# If the word is already in the dictionary, increment its count
if word in word_counts:
word_counts[word] += 1
# If the word is not yet in the dictionary, add it with a count of 1
else:
word_counts[word] = 1
# Print the resulting word count dictionary
print(word_counts)
Step-by-step explanation:
This code uses the open() function to open the "text.txt" file for reading, and then reads each line of the file using a for loop. Each line is split into individual words using the split() method, and then each word is cleaned up by removing any punctuation and converting it to lowercase. The code then adds each word to a dictionary and counts the number of occurrences of each word. Finally, the resulting dictionary of word counts is printed to the console.