我的函数将字符串作为输入,它是文件的名称,应返回字典。字典将具有键/值对,其中键是与单词长度对应的整数,值是文件中出现的具有该长度的单词数。
该文件包含以下句子:
and then the last assignment ended and everyone was sad
理论上,返回的词汇看起来像这样:
{ 3:5, 4:2, 5:1, 8:1, 10:1}
到目前为止,我有这个:
"""
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()
这句话只是一个例子,我需要做到这一点,以便任何输入都可以。任何有关解决这个问题的帮助都将不胜感激。
答案 0 :(得分:0)
对于句子中的每个单词,您需要在字典中添加一个条目,其中单词的长度是关键:
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