看实验楼的课程,有一个小练习,做了一下。要求用Python实现计算一段文本中每个单词出现的次数。
sentence = 'hello world nihao world hey hello java world hi python yeoman Word'#先把字符串分割成单个单词列表list1 = sentence.split() #['hello', 'world', 'nihao', 'world', 'hey', 'hello', 'java', 'world', 'hi', 'python', 'yeoman', 'word']PRint list1 #把列表转为结合,为了去除重复的项set1 = set(list1) #set(['java', 'python', 'word', 'nihao', 'hey', 'yeoman', 'hi', 'world', 'hello'])print set1 #把集合转为列表,集合元素没有顺序,没有索引属性,而列表有list2 = list(set1) #['java', 'python', 'word', 'nihao', 'hey', 'yeoman', 'hi', 'world', 'hello']print list2 #新建一个空的字典dir1 = {}for x in range(len(list2)): dir1[list2[x]] = 0 #字典值初始为0 for y in range(len(list1)): if list2[x] == list1[y]: dir1[list2[x]] += 1#{'word': 1, 'python': 1, 'nihao': 1, 'hey': 1, 'hello': 2, 'hi': 1, 'world': 3, 'java': 1, 'yeoman': 1}print dir1新闻热点
疑难解答