|
- #1.1 字符串:给定一个文章,找出每个单词的出现次数。例如给定下面的一篇短文,进行操作。
-
- str = "One is always on a strange road, watching strange scenery and listening to strange music. \
- Then one day, you will find that the things you try hard to forget are already gone. "
- n = len(str)
- #跳过列表
- skip_list = [' ','.','\n','\t']
- #记录单词和出现次数
- word_dict = dict()
- i = 0
- while i < n-1:
- if str[i] in skip_list:
- i += 1
- #读取一个单词
- word = ''
- while str[i] not in skip_list:
- word = word + str[i]
- i += 1
- #更新单词列表
- if word in word_dict:
- word_dict[word] += 1
- else:
- word_dict[word] = 1
- #删除空元素
- del word_dict['']
-
- print(word_dict)
|