【问题标题】:How do I make a Python Program demonstrating Zipf's Law?如何制作演示 Zipf 定律的 Python 程序?
【发布时间】: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


【解决方案1】:

这应该符合您的标准 - 我不确定您在代码末尾使用 for 循环做什么 - 您是否尝试替换数字?如果是这样,您可以更改我使用的正则表达式模式。

import re
from collections import OrderedDict

pattern = re.compile('[\W_]+')

def convertForZipf(string):
    string = string.lower()
    pattern.sub('', string)
    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:
    if i not in wordsRanked:
        wordsRanked[i] = 1
    else:
        wordsRanked[i] += 1

wordsRanked = OrderedDict(sorted(wordsRanked.items(), key=lambda t: t[1], reverse=True))

for k, v in wordsRanked.items():
    print(f"{k} appears {v} times.")

输出:

h appears 5 times.
n appears 5 times.
ipsum appears 3 times.
dolor appears 2 times.
lorem appears 1 times.
meow appears 1 times.

【讨论】:

    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    相关资源
    最近更新 更多