Python - 从一个文件到另一个文件打印统计信息

时间:2014-05-05 21:58:49

标签: python

import sys
import pickle
import string

def Menu():
    print ("***********MENU************")
    print ("0. Quit")
    print ("1. Read text file")
    print ("2. Display counts")
    print ("3. Display statistics of word lengths")
    print ("4. Print statistics to file")

def readFile():
    while True:
            fileName = input("Please enter a file name: ")
        if (fileName.lower().endswith(".txt")):
                break
        else:
                print("That was an incorrect file name. Please try again.")
        continue
    return fileName


THE_FILE = ""
myDictionary = 0

def showCounts(fileName):    
    numCount = 0
    dotCount = 0
    commaCount = 0
    lineCount = 0
    wordCount = 0

    with open(fileName, 'r') as f:
            for line in f:
                wordCount+=len(line.split())
                lineCount+=1
                for char in line:
                        if char.isdigit() == True:
                            numCount+=1
                        elif char == '.':
                            dotCount+=1
                        elif char == ',':
                            commaCount+=1

    print("Number count: " + str(numCount))
    print("Comma count: " + str(commaCount))
    print("Dot  count: " + str(dotCount))
    print("Line count: " + str(lineCount))
    print("Word count: " + str(wordCount))

def showStats(fileName):
    temp1 = []
    temp2 = []
    lengths = []
    myWords = []
    keys = []
    values = []
    count = 0

    with open(fileName, 'r') as f:
        for line in f:
            words = line.split()
            for word in words:
                temp2.append(word)
                temp1.append(len(word))

        for x in temp1:
            if x not in lengths:
                lengths.append(x)

        lengths.sort()

    dictionaryStats = {}
    for x in lengths:
        dictionaryStats[x] = []

    for x in lengths:
        for word in temp2:
            if len(word) == x:
                dictionaryStats[x].append(word)

    for key in dictionaryStats:
        print("Key = " + str(key) + " Total number of words with " + str(key) + " characters = " + str(len(dictionaryStats[key])))        
    return dictionaryStats

def printStats(aDictionary):
    aFile = open("statsWords.dat", 'w')
    for key in aDictionary:
        aFile.write(str(key) + " : " +  str(aDictionary[key]) + "\n")        
    aFile.close()

choice = -1

while choice !=0:
    Menu()
    choice = (int(input("Please choose 1-4 to perform function. Press 0 to exit the program. Thank you. \n")))
    if choice == 0:
        print ("Exit program. Thank you.")
        sys.exit
    elif choice == 1:
            THE_FILE = readFile()
    elif choice == 2:
            showCounts(THE_FILE)
    elif choice == 3:
            showStats(THE_FILE)
    elif choice == 4:
            printStats(myDictionary)        
    else: 
        print ("Error.")

我正在尝试打开一个文件,让它显示字长的统计信息,然后让它创建一个带有字长统计信息的新文件。我可以读取文件并让它显示统计信息,但是当我将统计信息打印到文件时,我得到一个错误 - “int”对象不可迭代。有任何想法吗?谢谢你们!

Error:

Traceback (most recent call last):
  File "hw4_ThomasConnor.py", line 111, in <module>
    printStats(myDictionary)        
  File "hw4_ThomasConnor.py", line 92, in printStats
    for key in aDictionary:
TypeError: 'int' object is not iterable

2 个答案:

答案 0 :(得分:1)

问题是您将myDictionary设置为程序顶部的0,然后将其发送到您的文件写入功能printStats(myDictionary)

在此功能中,您有for key in aDictionary这一行,并且在您传入0后,这实际上是for key in 0,这是错误的来源。

您需要将showStats功能的结果发送到printStats功能。

由于这看起来像是家庭作业,我现在就把它留在那里。


  抱歉,我很困惑。在showStats函数我不得不以某种方式说   &#34;将结果发送到printStats函数&#34;然后在printStats中   功能我要调用结果?我该怎么做呢?

printStats函数需要打印字典。这个字典是由showStats函数生成的(事实上,它返回这个字典)。

所以你需要将showStats函数的结果发送到printStats函数。

要保存方法的返回值,可以在调用表达式的LHS(左侧)上分配它,如下所示:

>>> def foo(bar):
...    return bar*2
...
>>> def print_results(result):
...    print('The result was: {}'.format(result))
...
>>> result = foo(2)  # Save the returned value

由于result与Python中的任何其他名称一样,您可以将其传递给任何其他函数:

>>> print_results(result)
The result was: 4

如果我们不想存储函数的结果,只想将其发送到另一个函数,那么我们可以使用以下语法:

>>> print_results(foo(2))
The result was: 4

您需要在执行函数的主循环中执行类似的操作。

由于showStats函数返回了要打印的字典,因此必须先调用showStats函数,然后再调用printStats函数。如果您的用户在选择3之前选择4,则会出现问题 - 请确保找到解决方法。一个简单的解决方法是在选择之前通过选择3来提示用户计算统计数据。试着想出另一种方法来解决这个问题。

答案 1 :(得分:0)

下面:

THE_FILE = ""
myDictionary = 0

您将整数设置为myDictionary

以后再做:

printStats(myDictionary)

当你尝试在里面对词典的键进行交互时,你会失败。