Python实现计算一段文本中每个单词出现的次数

来源:互联网 发布:php class unset 编辑:程序博客网 时间:2024/06/05 02:28


看实验楼的课程,有一个小练习,做了一下。要求用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  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

阅读全文
0 0
原创粉丝点击