lintcode-2174 · 查询文件中单词 ‘your’ 的个数

998 阅读1分钟

描述

请编写 Python 代码,实现名为 num_your 的函数。该函数将统计文件中单词 ‘your’ 出现的次数,最后返回统计值。

请在 solution.py 中编写 num_your 函数的代码,我们会在 main.py 中通过导入的方式运行你的代码,以检测是否正确完成以上功能。

**

  • 所统计单词的大小写需要一致
  • 查找的单词 your 前后需要空格,保证只查找到单词 your

样例

测评机会通过执行 python main.py 来执行你的代码。

样例一:

若要查询的文件中内容为:

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.

则读取该文件并统计单词 “your” 的数量并打印出的结果为:

1

样例二:

若要查询的文件中内容为:

When You are Old 
        By William Butler Yeats (1865-1939When 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.

则读取该文件并统计单词 “your” 的数量并打印出的结果为:

3

题解

Python count() 方法用于统计字符串里某个字符或子字符串出现的次数。可选参数为在字符串搜索的开始与结束位置。

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