查找文本中的前5个单词长度

时间:2016-04-21 05:49:00

标签: list function python-3.x testing string-length

我正在尝试编写一个带有两个函数的程序:

  1. count_word_lengths ,它接受参数 text ,一个文本字符串,并返回一个记录每个字长的计数的默认字典。调用此函数的示例:

  2. top5_lengths ,它使用相同的参数 text 并返回前5个字长的列表。

  3. 注意:如果是这样的话 两个长度具有相同的频率,它们应按降序排序。此外,如果字长少于5个,则应返回较短的有序字长列表。

    示例调用 count_word_lengths

    count_word_lengths("one one was a racehorse two two was one too"):
         defaultdict(<class 'int'>, {1: 1, 3: 8, 9: 1})
    

    示例调用 top5_lengths

    top5_lengths("one one was a racehorse two two was one too")
        [3, 9, 1]
    
    top5_lengths("feather feather feather chicken feather")
        [7]
    
    top5_lengths("the swift green fox jumped over a cool cat")
        [3, 5, 4, 6, 1]
    

    我当前的代码就是这样,似乎输出了所有这些调用,但是它没有进行隐藏测试。我没有考虑什么类型的输入?我的代码实际上是否正常运行?如果没有,我该如何解决这个问题?

    from collections import defaultdict
    
    length_tally = defaultdict(int)
    final_list = []
    
    def count_word_lengths(text):
        words = text.split(' ')
    
        for word in words:
            length_tally[len(word)] += 1
    
        return length_tally
    
    
    def top5_word_lengths(text):
        frequencies = count_word_lengths(text)
        list_of_frequencies = frequencies.items()
        flipped = [(t[1], t[0]) for t in list_of_frequencies]
        sorted_flipped = sorted(flipped)
        reversed_sorted_flipped = sorted_flipped[::-1]
    
    
        for item in reversed_sorted_flipped:
            final_list.append(item[1])
    
        return final_list
    

3 个答案:

答案 0 :(得分:1)

需要注意的一点是,您没有考虑空字符串。这将导致count()返回null / undefined。你也可以在列表理解期间使用iteritems()来获取像for k,v in dict.iteritems():

这样的字典中的键和值。

答案 1 :(得分:0)

我不是Python人,但我可以看到一些可能导致问题的事情。

  • 您一直在引用top5_lengths,但您的代码有一个名为top5_word_lengths的函数。
  • 您使用的名为count_lengths的函数未在任何地方定义。

解决这些问题,看看会发生什么!

修改: 这不应该影响您的代码,但是您的函数更新范围之外的变量并不是很好的做法。您可能希望将顶部的变量赋值移动到使用它们的函数。

答案 2 :(得分:0)

不是一个真正的答案,而是一种跟踪单词而非长度的替代方法:

from collections import defaultdict

def count_words_by_length(text):
   words = [(len(word),word) for word in text.split(" ")]
   d = defaultdict(list)
   for k, v in words:
      d[k].append(v)
   return d


def top_words(dict, how_many):
    return [{"word_length": length, "num_words": len(words)} for length, words in dict.items()[-how_many:]]

使用如下:

my_dict = count_words_by_length('hello sir this is a beautiful day right')
my_top_words = num_top_words_by_length(my_dict, 5)

print(my_top_words)
print(my_dict)

输出:

[{'word_length': 9, 'num_words': 1}]
defaultdict(<type 'list'>, {1: ['a'], 2: ['is'], 3: ['sir', 'day'], 4: ['this'], 5: ['hello', 'right'], 9: ['beautiful']})