179k views
2 votes
Write a function called word_count. This function will accept one argument, which will be a file path to a file. The function will read this file and return a dictionary that has the counts of each word in the file. a

User Cusmar
by
8.4k points

1 Answer

1 vote

Step-by-step explanation:

Certainly! Here's an example of the `word_count` function in Python that reads a file and returns a dictionary with the counts of each word in the file:

```python

def word_count(file_path):

word_counts = {}

# Open the file in read mode

with open(file_path, 'r') as file:

# Read each line in the file

for line in file:

# Split the line into words

words = line.strip().split()

# Count the occurrence of each word

for word in words:

if word in word_counts:

word_counts[word] += 1

else:

word_counts[word] = 1

return word_counts

```

You can use this function by providing the file path as an argument. For example:

```python

file_path = 'path/to/your/file.txt'

counts = word_count(file_path)

print(counts)

```

Make sure to replace `'path/to/your/file.txt'` with the actual path to your file. The function will read the file, count the occurrences of each word, and return a dictionary where the keys are the words and the values are their respective counts.

User AdamJonR
by
7.7k points