【发布时间】:2020-05-05 14:20:00
【问题描述】:
对于当前的研究项目,我计划测量 JSON 文件中唯一单词的相对出现次数。目前,我有一个指示文件中唯一单词的数量及其相应的出现次数(例如"technology":"325"),但我仍然缺乏一个完整的字数统计方法。
我用于完整字数统计的代码(total = sum(d[key])) 会产生以下通知。我已经检查了一些类似问题的解决方案,但尚未找到适用的答案。有什么聪明的方法可以解决这个问题吗?
total = sum(d[key]) - TypeError: 'int' object is not iterable
对应的代码部分如下所示:
# Create an empty dictionary
d = dict()
# processing:
for row in data:
line = row['Text Main']
# Remove the leading spaces and newline character
line = line.strip()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()
# Remove the punctuation marks from the line
line = line.translate(line.maketrans("", "", string.punctuation))
# Split the line into words
words = line.split(" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
# Print the contents of dictionary
for key in list(d.keys()):
print(key, ":", d[key])
# Count the total number of words
total = sum(d[key])
print(total)
【问题讨论】:
-
total = sum(d.values()) -
非常感谢 - 这就是我想要的。 :)