【发布时间】:2019-11-19 11:59:01
【问题描述】:
齐夫定律是在许多现实生活中发现的模式,齐夫定律非常常见的出现在文本段落中,其中最常用的词是第二常用词的两倍。
我一直在学习 Python 中的字典并尝试自己做这件事,但对它们的某些方面感到困惑。
第一步应该首先从字符串中删除标点符号(这是为了防止下一步出现'to'或'said-'之类的词),然后将.split放入列表中。然后,创建一个字典,键是单词,值是它们的出现,这可以使用for 循环来完成。然后,我怀疑最困难的部分可能是按降序打印所有键和值。
如果不是整个代码,您能告诉我如何完成每一步,以便我自己完成吗?谢谢!
import operator, pprint
punctuater = ['`','~','!','@','#','$','%','*','(',')','-', \
'_','+','=','[','\]','{','}','|','\\','\"','\'', \
':',';','<',',','>','.','/','?','^','&']
numbers = [1,2,3,4,5,6,7,8,9,0]
def convertForZipf(string):
string = (string.lower())
for i in punctuater:
if i in string:
string = string.replace(i, '')
return string.split()
text = 'Lorem Ipsum Ipsum Ipsum Meow h h h h h n n n n n dolor dolor'
words = convertForZipf(text)
wordsRanked = {}
for i in words:
wordsRanked.setdefault(i, 0)
wordsRanked[i] += 1
wordsRanked = (str((sorted(wordsRanked.items(), key=operator.itemgetter(1), reverse=True))))
for i in wordsRanked:
try:
int(i)
wordsRanked = wordsRanked.replace(str(i), str(i)+'\n')
except ValueError:
pass
print((wordsRanked.replace('[','')
.replace('(','')
.replace(')','')
.replace(']','')
.replace(',',' : ')))
在我正式完成这个项目之前,我只需要最后一件事的帮助,我的输出显示有问题,我的代码高度不一致,我愿意接受建议。
【问题讨论】:
-
对于“最困难的部分”,请查看 Counters docs.python.org/3/library/collections.html#collections.Counter。我最喜欢的 Python 功能之一 :)
-
attempted to do this myself- 请向我们展示您目前拥有的代码! -
@TomDalton 我已在链接中添加,它不是最好的代码,但它(有点)有效。我很想看看你的看法!
标签: python python-3.x string list dictionary