代码未正确搜索文本文件

时间:2017-07-26 23:30:32

标签: python python-3.x text-files

#
# Obtain user input for file name, and open it
#
inFile = open(input("Enter file name: "), "r")
#
# Process data and address possible errors
#
countDinner = 0
countLodging = 0
countConference = 0
valueDinner = 0
valueLodging = 0
valueConference = 0
done = False
while not done :
line = inFile.readline()
try :
    s = line
    serviceAmount = ';'.join(s.split(';')[1:-1]) #Removes date and name regardless of format
    serviceAmount.split(";")
    s.lower()
    if "dinner" in s :
        countDinner = countDinner + 1
        valueDinner = valueDinner + int(filter(str.isdigit, s))
        print("Dinners: ", countDinner, "Value of Dinner sales: ", valueDinner)
    elif "lodging" in s :
        countLodging = countLodging + 1
        valueLodging = valueLodging + int(filter(str.isdigit, s))
        print("Lodging: ", countLodging, "Value of Lodging sales: ", valueLodging)
    elif "conference" in s :
        countConference = countConference + 1
        valueConference = valueConference + int(filter(str.isdigit, s))
        print("Conferences: ", countConference, "Value of Conference sales: ", valueConference)
    elif line == "" :
        done = True
    else :
        print("Invalid file format.")
except FileNotFoundError :
    print("Unable to find file.")
finally :
    done = True
    inFile.close()

即使专门为此代码设置了文档,也会返回“文件格式无效”。我没有收到语法错误,所以我不确定是不是错了。 该文件包含文字:

John;Lodging;123;050617 
Tyler;Conference;123;081497 
Taylor;Dinner;453;041798 

3 个答案:

答案 0 :(得分:0)

这是你的问题:

serviceAmount = ';'.join(s.split(';')[1:-1]) #Removes date and name regardless of format
serviceAmount.split(";")

你应该这样做:

serviceAmount = ';'.join(s.lower().split(';')[1:-1])

您正在检查小写字符串,但实际上并未降低输入的大小。

同样重要的是要注意s.lower()实际上更改 s,它只会返回一个字符串,其中s的所有字母都已被删除切换到小写。 split也是一样的(因为没有改变它被调用的字符串,而不是它返回一个字符串)。

您将遇到的另一个问题是从字符串中获取数字。

int(filter(str.isdigit, s))

不行。您可以像之前一样再次使用split(或者只是不重新join,因为您只关心比较中的第一个元素。)

int(serviceAmount.split(';')[1])

最后一件事是

finally:
    done = True
    inFile.close()

finally总是在退出try时运行,这意味着你总是在每次循环后完成(并在读完第一行后关闭文件)。

如果您移除finally并在inFile.close()内添加elif line == "",它将关闭,并且仅在您到达文件末尾时设置done。< / p>

答案 1 :(得分:0)

有很多事情你在这里没有做得很好。我试图解决你发布的问题,但也写了一些应该更清晰,更容易使用的代码。我留下了评论来解释事情。

# Don't open the file here, just get the file name. We will open in later
fname = input("Enter file name: ")

# I think using dicts is more clearn and organized. Having so many variables I think makes the code messy
counts = {"Dinner": 0,
"Lodging": 0,
"Conference": 0}

values = {"Dinner": 0,
"Lodging": 0,
"Conference": 0}

# Lets try to open the file
try:
    with open(fname, 'r') as inFile: # Use "with", this way the file is closed automatically when we are done reading it
        for linenum, line in enumerate(inFile): # I want to enumerate each line. If there is an error on a line, we can display the line nmber this way
            line = line.lower().split(';')[1:-1] # lets make it all lower case, then split and drop as needed
            print(line)
            if "dinner" in line :
                counts["Dinner"] += 1 # x += 1 is the same as x = x + 1, but cleaner
                values["Dinner"] += int(line[1])
                print("Dinners: {} Value of Dinner sales: {}".format(counts["Dinner"], values["Dinner"]))
            elif "lodging" in line :
                counts["Lodging"] += 1
                values["Lodging"] += int(line[1])
                print("Lodging: {} Value of Dinner sales: {}".format(counts["Lodging"], values["Lodging"]))
            elif "conference" in line :
                counts["Conference"] += 1
                values["Conference"] += int(line[1])
                print("Conference: {} Value of Dinner sales: {}".format(counts["Conference"], values["Conference"]))
            else :
                print("Invalid file format on line {}".format(linenum)) # Here is why we used enumerate in the for loop
except FileNotFoundError: 
    print("Unable to find file.")

答案 2 :(得分:0)

可以像

一样简单
categories = {}

filename = input("Enter file name: ")

with open(filename, "r") as file:

    name, category, value, date = file.readline().split(";")

    if category not in categories:
        categories[category] = {"count": 0, "value": 0}

    categories[category]["count"] += 1
    categories[category]["value"] += int(value)

最后,你会有一个包含类别,数量和价值的字典,而且它们的名字也不是硬编码的。