出现相同长度的单词 [英] Occurrence of words with same length

查看:54
本文介绍了出现相同长度的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的函数将字符串作为文件名输入,并应返回字典.该词典将具有键/值对,其中键是对应于单词长度的整数,而值是具有该长度的文件中出现的单词数.

My function takes a string as input that is the name of a file and should return a dictionary. The dictionary will have key/value pairs where keys are integers that correspond to word lengths and the values are the number of words that appear in the file with that length.

文件由以下句子组成:

and then the last assignment ended and everyone was sad

因此,理论上返回的字典将如下所示:

So theoretically the returned diction would look like this:

{ 3:5, 4:2, 5:1, 8:1, 10:1}

到目前为止,我有这个:

So far I have this:

"""
COMP 1005 - Fall 2016
Assignment 10
Problem 1
"""
def wordLengthStats(filename):
    file = open(filename, 'r')
    wordcount={}
    for line in file.read().split():
        if line not in wordcount:
            wordcount[line] = 1
        else:
            wordcount[line] += 1
    for k,v in wordcount.items():
        print (k, v)
    return None

def main():
    '''
    main method to test your wordLengthStats method
    '''
    d = wordLengthStats("sample.txt")
    print("d should be { 3:5, 4:2, 5:1, 8:1, 10:1} ")
    print("d is", d)

if __name__ == '__main__':
    main()

这句话只是一个例子,我需要使它成为可能,以便任何输入都可以工作.对于解决此问题的任何帮助将不胜感激.

The sentence is just an example, I need to make it so that any input should work. Any help on approaching this problem would be greatly appreciated.

推荐答案

对于句子中的每个单词,您都需要在字典中添加一个条目,其中单词的长度是关键:

For every word in the sentence, you need to add an entry to the dictionary where the length of the word is the key:

def wordLengthStats(filename):
    file = open(filename, 'r')
    wordcount={}
    for word in file.read().split():

        key = len(word)

        if key not in wordcount:
            wordcount[key] = 1
        else:
            wordcount[key] += 1

    for k,v in wordcount.items():
        print (k, v)                               
    return None

这篇关于出现相同长度的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆