2013-07-14 46 views
1

这个程序我试图问他/她想要在一个文件中并有计划数已存储在该文件中的单词总数输入用户尽可能多的文本。例如,如果我输入“你好,我喜欢吃蓝莓派”,那么这个程序应该总共阅读7个字。该程序运行良好,直到我输入选项6,它计算单词的数量。我总是得到这个错误:“海峡”对象有没有属性“项目”Python:计算文件中单词的总数?

#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) 

回答

5

这里的问题是,textInput是一个字符串,因此它不具有items()方法。

如果你只是想单词的数量,你可以尝试使用LEN:

print len(textInput.split(' ')) 

如果你想每一个字,以及它们各自的发生,你需要使用count,而不是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

谢谢你的帮助! – user2581724

+3

顺便说一句,不带参数的'.split()'会删除任何包含新行和标签的空白字符。 '.split('')'将只删除由空格分隔的单词。 – OdraEncoded

0

要计算单词总数(包括重复次数),可以使用此单行文本,其中file_path是文件的绝对路径:

sum(len(line.split()) for line in open(file_path))