我正在尝试编写一个代码,该代码从用户输入一行,将其拆分并将其提供给名为 counts 的 majestic 字典。一切都很好,直到我们向女王陛下询问一些数据。我希望数据的格式是首先打印单词并在其旁边打印重复的次数。下面是我设法编写的代码。
counts = dict()
print('Enter a line of text:')
line = input('')
words = line.split()
print('Words:', words)
print('Counting:')
for word in words:
counts[word] = counts.get(word,0) + 1
for wording in counts:
print('trying',counts[wording], '' )
当它执行时,它的输出是不可原谅的。
Words: ['You', 'will', 'always', 'only', 'get', 'an', 'indent', 'error', 'if', 'there', 'is', 'actually', 'an', 'indent', 'error.', 'Double', 'check', 'that', 'your', 'final', 'line', 'is', 'indented', 'the', 'same', 'was', 'as', 'the', 'other', 'lines', '--', 'either', 'with', 'spaces', 'or', 'with', 'tabs.', 'Most', 'likely,', 'some', 'of', 'the', 'lines', 'had', 'spaces', '(or', 'tabs)', 'and', 'the', 'other', 'line', 'had', 'tabs', '(or', 'spaces).']
Counting:
trying 1
trying 1
trying 1
trying 1
trying 1
trying 2
trying 2
trying 1
trying 1
trying 1
trying 2
trying 1
trying 1
trying 1
trying 1
trying 1
trying 1
trying 1
trying 2
它只打印尝试和重复的次数,没有单词(我认为它在字典中被称为索引,如果我错了,请纠正我)
Thankyou
请帮助我,在回答这个问题时请记住我是一个新手,无论是python还是堆栈溢出。
答案 0 :(得分:2)
在你的代码中没有任何地方试图打印这个词。您如何期望它出现在输出中?如果你想要这个词,把它放在要打印的东西列表中:
print(wording, counts[wording])
要了解更多信息,请查找包 collections
,并使用 Counter
构造。
counts = Counter(words)
将为您计算所有字数。
答案 1 :(得分:1)
您应该使用 counts.items()
迭代 counts
的键和值,如下所示:
counts = dict()
print('Enter a line of text:')
line = input('')
words = line.split()
print('Words:', words)
print('Counting:')
for word in words:
counts[word] = counts.get(word,0) + 1
for word, count in counts.items(): # notice this!
print(f'trying {word} {count}')
另请注意,您可以在打印时使用 f 字符串。
答案 2 :(得分:1)
我很困惑为什么要打印 trying
。
试试这个。
counts = dict()
print('Enter a line of text:')
line = input('')
words = line.split()
print('Words:', words)
print('Counting:')
for word in words:
counts[word] = counts.get(word,0) + 1
for wording in counts:
print(wording,counts[wording], '' )
答案 3 :(得分:1)
您拥有的代码遍历字典键并仅打印字典中的计数。你会想要做这样的事情:
for word, count in counts.items():
print('trying', word, count)
您可能还想使用
from collections defaultdict
counts = defaultdict(lambda: 0)
所以在添加到字典时,代码会像
一样简单counts[word] += 1