Python
Write function stringCount() that takes two string inputs—a file name and a target string— and returns the number of occurrences of the target string in the file.
>>> stringCount('example.txt', 'line')
4
def stringCount(fname, target):
# reading file and taking words into a list
f = open(fname)
r = f.read().split()
# counting the occurrences of target string
count = 0
for one in r:
if one == target:
count += 1
f.close()
# returning the count
return count
print(stringCount('example.txt', 'line'))
# Hit the thumbs up if you are fine with the answer. Happy Learning!
Get Answers For Free
Most questions answered within 1 hours.