• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

describe

Write Python code to implement a function named num_your. This function counts the number of occurrences of the word ‘your’ in the file and returns the statistics.

Please code the num_your function in solution.py, and we will run your code in main.py by importing it to check that the above functions are done correctly.

**

  • The case of the counted words must be the same
  • Use a space before and after the word “your” to ensure that only the word “your” is found

The sample

The tester will execute your code by executing Python main.py.

A sample:

The contents of the file to be queried are as follows:

A Grain of Sand
    By William Blake
To see a world in a grain of sand,
And a heaven in a wild fllower,
Hold infinity in the palm of your hand,
And eternity in an hour.
Copy the code

Then read the file and count the number of words “your” and print the result:

1
Copy the code

Example 2:

The contents of the file to be queried are as follows:

When You are Old By William Butler Yeats (1865-1939) When You are Old and gray and full of sleep And nodding by the fire, take down this book, And slowly read, and dream of the soft look Your eyes had once, and of their shadows deep; How many loved your moments of glad grace, And loved your beauty with love false or true, But one man loved the pilgrim soul in you, And loved the sorrows of your changing face; And bending down beside the glowing bars, Murmur, a little sadly, how Love fled And paced upon the mountains overhead And hid his face among a crowd of stars.Copy the code

Then read the file and count the number of words “your” and print the result:

3
Copy the code

Answer key

The Python count() method counts the number of occurrences of a character or substring in a string. Optional arguments are the start and end positions of the string search.

def num_your(poem):
	s = " your "
	a = poem.count(s)
	return a
Copy the code