为什么我的python单词计数程序不起作用?

时间:2018-09-19 09:20:05

标签: python python-3.x

我正在上一门python课程,其中一个问题要我写一个程序来计算像这样的单词:

Enter line: which witch
Enter line: is which
Enter line: 
is 1
which 2
witch 1

到目前为止,我的代码是:

occurences = {}

line = input('Enter line: ')
while line:
  m = line.split()
  for i in m:
    if i in occurences:
      occurences[i] += 1
    else:
      occurences[i] = 1
    line = input('Enter line: ')


for word in sorted(occurences):
  print(word, occurences[word])

但是当我运行这段代码时,它要么告诉我每个单词只出现一次,要么告诉我其他奇怪的输出。感谢您的帮助!

这是一个不起作用的示例:

Enter line: test test test
Enter line: one two test
Enter line: one
Enter line: 
test 3

这是我得到的输出,而预期的输出是:

test 4
two 1
one 2

3 个答案:

答案 0 :(得分:1)

您在for循环中输入的内容会引起问题,请尝试以下操作:

occurences = {}

line = input('Enter line: ')
while line:
  m = line.split()
  print( m)
  for i in m:

    if i in occurences:
      occurences[i] += 1
    else:
      occurences[i] = 1

    print(occurences)
  line = input('Enter line: ')


for word in sorted(occurences):
  print(word, occurences[word])

通过在f​​or循环中重置输入,您需要在计算第一个单词之后请求新的输入,而忽略字符串中的后续单词。

答案 1 :(得分:-1)

您可以简单地做到这一点

m = line.split()
for i in m:
     print(line.count(i), word)

答案 2 :(得分:-1)

当我运行代码时,我根本没有任何输出,这是因为您有一个无限循环,方法是在“ While”循环的末尾询问用户另一行,这会导致它无限执行。

为了与您所做的事情相匹配,在我稍稍更改代码之前

occurences = {}
line = input('Enter line: ')

while line:
    m = line.split()
    for i in m:
        if i in occurences:
            occurences[i] += 1
        else:
            occurences[i] = 1
    break ## Once the word has been put into occurences it breaks
          ##    so that the next loop can run  


for word in sorted(occurences):
    print(word, occurences[word])

如果您希望它一直持续到用户退出程序,那么您可以这样做:

while True:
    occurences = {}
    line = input('Enter line: ')

    while line:
        m = line.split()
        for i in m:
            if i in occurences:
                occurences[i] += 1
            else:
                occurences[i] = 1
        break

    for word in sorted(occurences):
        print(word, occurences[word])