python计算单词数量_Python:计算文件中的单词总数吗?

for this program I'm trying to ask the user enter as much text as he/she wants in a file and have the program count the Total number of words that was stored in that file. For instance, if I type "Hi I like to eat blueberry pie" the program should read a total of 7 words. The program runs fine until I type in Option 6, where it counts the number of words. I always get this error: 'str' object has no attribute 'items'

#Prompt the user to enter a block of text.

done = False

textInput = ""

while(done == False):

nextInput= input()

if nextInput== "EOF":

break

else:

textInput += nextInput

#Prompt the user to select an option from the Text Analyzer Menu.

print("Welcome to the Text Analyzer Menu! Select an option by typing a number"

"\n1. shortest word"

"\n2. longest word"

"\n3. most common word"

"\n4. left-column secret message!"

"\n5. fifth-words secret message!"

"\n6. word count"

"\n7. quit")

#Set option to 0.

option = 0

#Use the 'while' to keep looping until the user types in Option 7.

while option !=7:

option = int(input())

#I get the error in this section of the code.

#If the user selects Option 6, print out the total number of words in the

#text.

elif option == 6:

count = {}

for i in textInput:

if i in count:

count[i] += 1

else:

count[i] = 1

#The error lies in the for loop below.

for word, times in textInput.items():

print(word , times)

解决方案

The issue here is that textInput is a string, so it doesn't have the items() method.

If you only want the number of words, you can try using len:

print len(textInput.split(' '))

If you want each word, and their respective occurrences, you need to use count instead of textInput:

count = {}

for i in textInput.split(' '):

if i in count:

count[i] += 1

else:

count[i] = 1

for word, times in count.items():

print(word , times)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值