版权声明:欢迎联系我转载!欢迎交流分享!转载和分享请注明出处! https://blog.csdn.net/u014303046/article/details/82555511
Popular words
一、问题描述
要求:统计字符串中每个单词的频率,按照出现频率从高到低给出词汇字典。
输入:字符串和需要搜索的词汇列表
输出:词汇字典(键:需要搜索的词汇;值:词频)
注意:
- 比如One, one, ONE等视为同样的单词
- 对于未找到的单词,频率为0
示例:
popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']) == {
'i': 4,
'was': 3,
'three': 0,
'near': 0
}
二、解题示例
1. 遍历
def popular_words(text: str, words: list) -> dict:
# your code here
text = text.lower().split()
popular_words = dict(zip(words, [0 for _ in range(len(words))]))
for item in text:
if item in words:
popular_words[item] += 1
return popular_words
if __name__ == '__main__':
print("Example:")
print(popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']))
# These "asserts" are used for self-checking and not for an auto-testing
assert popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']) == {
'i': 4,
'was': 3,
'three': 0,
'near': 0
}
print("Coding complete!")
2. count函数
def popular_words(text, words):
lower_count = text.lower().split().count
return {word: lower_count(word) for word in words}
if __name__ == '__main__':
print("Example:")
print(popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']))
# These "asserts" are used for self-checking and not for an auto-testing
assert popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']) == {
'i': 4,
'was': 3,
'three': 0,
'near': 0
}
print("Coding complete!")
3.
def popular_words(text, words):
return dict(zip(words, map(text.lower().split().count, words)))
if __name__ == '__main__':
print("Example:")
print(popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']))
# These "asserts" are used for self-checking and not for an auto-testing
assert popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']) == {
'i': 4,
'was': 3,
'three': 0,
'near': 0
}
print("Coding complete!")