【问题标题】:the code for counting frequency plot of letters in abody text in python在python中计算正文中字母频率图的代码
【发布时间】:2016-12-21 06:49:26
【问题描述】:

我正在编写一个程序,该程序可以生成正文中字母的频率图。但是,我的代码中有一个错误,我无法发现它。有什么想法吗?

def letter_count(word,freqs,pmarks):
for char in word:
    freqs[char]+=1
def letter_freq(fname):
fhand = open(fname)
freqs = dict()
alpha = list(string.uppercase[:26])
for let in alpha: freqs[let] = freqs.get(let,0)
for line in fhand:
    line = line.rstrip()
    words = line.split()
    pmarks = list(string.punctuation)
    words = [word.upper() for word in words]
    for word in words:
        letter_count(word,freqs,pmarks)                                                                                   
 fhand.close()

return freqs.values

【问题讨论】:

  • 嘿Alqosh。我猜你知道缩进在 python 中很重要。请在您的代码上使用正确的缩进来运行它或使其易于理解以获得进一步的帮助:)
  • 缩进不是问题(我的意图在我的 python 中是正确的)。我收到此错误消息: KeyError: ' 。 '我以前从未见过它
  • 嗯,了解正确的缩进对每个想要提供帮助的人都有帮助。
  • 你是对的。但正如我所说,问题不在于缩进。我需要测试第 3 行中的 [char] 是否是标点符号,然后更新 freqs[char]

标签: python-2.7


【解决方案1】:

你在打电话

freqs[char]+=1

使用 char = '.'没有初始化值 freqs['.']=0

您应该在第 3 行之前检查该键是否已经存在,因为您只能对字典的现有键执行 +=1 操作。

比如:

for char in word:
    if freqs.has_key(char):
        freqs[char]+=1

Python: how can I check if the key of an dictionary exists?

【讨论】:

  • 所以,我应该找出'char'是否是标点符号。然后更新freqs[char]?
  • 更新我的答案
猜你喜欢
  • 2020-10-04
  • 2021-12-31
  • 2015-06-15
  • 2012-10-24
  • 2017-04-20
  • 2019-06-04
  • 2023-03-25
  • 1970-01-01
相关资源
最近更新 更多