Python:计算文件中的单词总数吗? [英] Python: Count the Total number of words in a file?
问题描述
对于该程序,我试图要求用户在文件中输入尽可能多的文本,并让程序计算该文件中存储的单词总数。例如,如果我键入我喜欢吃蓝莓派,则该程序应总共读取7个单词。该程序可以正常运行,直到我键入Option 6为止,在其中可以计算单词数。我总是收到此错误:'str'对象没有属性'items'
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)
推荐答案
此处的问题是 textInput
是一个字符串,因此它没有 items()
方法。
The issue here is that textInput
is a string, so it doesn't have the items()
method.
如果只需要单词数,可以尝试使用len:
If you only want the number of words, you can try using len:
print len(textInput.split(' '))
如果您想要每个单词及其各自的出现,则需要使用 count
而不是 textInput
:
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)
这篇关于Python:计算文件中的单词总数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!