【问题标题】:Python: Count the Total number of words in a file?Python:计算文件中的总字数?
【发布时间】:2013-07-14 23:28:06
【问题描述】:

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

【问题讨论】:

    标签: python file text count words


    【解决方案1】:

    这里的问题是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)
    

    【讨论】:

    • 顺便说一下,.split() 不带参数会删除任何包含新行和制表符的空白字符。 .split(' ') 将只删除以空格分隔的单词。
    【解决方案2】:

    要统计总字数(包括重复),可以用这个单行,其中file_path是文件的绝对路径:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多