|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Let's mix the function, context manager, basic data structures, loops, conditional executions, statement
assignment, and f strings concepts and syntax we have learnt so far to solve this problem.
You may use the sample file (iso.txt) shared on Ed code section to test your code.
Hint:
Read file use open( ) function;
Split lines using split( ) function;
You may also count words use get( ) function to simplify a bit.
The get() method returns the value of the item with the specified key.
Syntax: dictionary.get(keyname, value)
keyname (Required) - The keyname of the item you want to return the value from
value (Optional) - A value to return if the specified key does not exist. Default value None
- # 打开文件并读取内容
- with open('iso.txt', 'r') as f:
- lines = f.read().splitlines()
- # 定义一个字典来存储单词的出现次数
- word_count = {}
- # 遍历每一行文本
- for line in lines:
- # 分割行成单词列表
- words = line.split()
- # 遍历每个单词
- for word in words:
- # 将单词添加到字典中并更新其出现次数
- word_count[word] = word_count.get(word, 0) + 1
- # 输出每个单词出现的次数
- for word, count in word_count.items():
- print(f"'{word}' 出现了 {count} 次")
复制代码
|
|