【问题标题】:Creating a dictionary of the words in a string, sorting by the number of occurrences, and only displaying words with 4 or more letters in them创建字符串中单词的字典,按出现次数排序,仅显示包含 4 个或更多字母的单词
【发布时间】:2020-06-07 17:06:10
【问题描述】:

方向:字典的键应该是单词,值应该是单词在段落中出现的次数,按降序对字典进行排序。仅显示包含 4 个或更多字母的单词。

text = """The goal is to turn data into information and information into insight . 
You can have data without information but you cannot have information without data ."""

我一直在解决这个问题,但似乎不能只显示包含 4 个或更多字母的单词。任何帮助将不胜感激,谢谢。

输出应该是

这是我目前所做的

# clean up string 'text'
for char in '-.,\n':
    text=text.replace(char,' ')
text = text.lower()
words_list = text.split(' ')

#define dictionary
words_dict = {}

#Count number of times each word comes up in list of words (in dictionary)
for word in words_list:
    if word not in words_dict:
        words_dict[word] = 0
    words_dict[word] += 1

#sort dictionary by number of occurences
sorted(words_dict.items(), key = lambda x: x[1], reverse = True)

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    对已发布代码的最小更改

    只在原始代码中添加了一个长度过滤器

    text = """The goal is to turn data into information and information into insight . 
    You can have data without information but you cannot have information without data ."""
    
    # clean up string 'text'
    for char in '-.,\n':
        text=text.replace(char,' ')
    text = text.lower()
    words_list = text.split(' ')
    
    #define dictionary
    words_dict = {}
    
    #Count number of times each word comes up in list of words (in dictionary)
    for word in words_list:
        if word not in words_dict:
            words_dict[word] = 0
        words_dict[word] += 1
    
    # Filter words
    filtered = {word:count for word,count in words_dict.items() if len(word) >= 4}
    
    #sort dictionary by number of occurences
    result = sorted(filtered.items(), key = lambda x: x[1], reverse = True)
    
    print('{:<15} {:<4}'.format('Word', 'Count'))
    for word, count in result:
      print(f'{word:15} {count:4}')
    

    输出

    Word            Count
    information        4
    data               3
    into               2
    have               2
    without            2
    goal               1
    turn               1
    insight            1
    cannot             1
    

    【讨论】:

      【解决方案2】:

      您可以在此处使用collections.Counterfilter

      from collections import Counter
      text = """The goal is to turn data into information and information into insight . 
      You can have data without information but you cannot have information without data ."""
      
      count = Counter(filter(lambda x:len(x)>=4, text.split()))
      
      sorted(count.items(),key = lambda x:x[1],reverse=True)
      [('information', 4),
       ('data', 3),
       ('into', 2),
       ('have', 2),
       ('without', 2),
       ('goal', 1),
       ('turn', 1),
       ('insight', 1),
       ('cannot', 1)]
      

      编辑: 不使用collections。您可以使用dict.setdefault 模仿Counter 的行为

      text = text.split()
      new = dict()
      
      for t in filter(lambda x:len(x)>=4,text):
          new[t] = new.setdefault(t,0) + 1
      
      sorted(new.items(),key=lambda x:x[1],reverse=True)
      

      【讨论】:

      • 似乎对我不起作用,与“new = dict()”部分混淆。当我尝试在你的 for 循环中使用我的“words_dict”字典时,它给了我与以前相同的结果
      • @MikeMB35 filter(lambda x:len(x)&gt;=4,text) 你错过了这部分。
      • @MikeMB35 for word in filter(lambda x:len(x)&gt;=4, word_list): 使用这个。
      猜你喜欢
      • 2011-09-10
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      • 1970-01-01
      相关资源
      最近更新 更多