python中单词个数_Python:计算一个文件中的单词总数?

对于这个程序,我试图要求用户在一个文件中输入他/她想要的文本,并让程序计算存储在该文件中的单词总数。例如,如果我输入“嗨,我喜欢吃蓝莓派”,程序应该总共读7个字。程序运行良好,直到我输入选项6,在那里它计算字数。我总是得到这个错误:“str”对象没有属性“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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值