Python,使用.dat文件中的数据

时间:2018-10-15 11:48:11

标签: python input

我是Python的新手,这个问题很基本,但仍然找不到正确的解决方案。

因此,我复制了一个名为“ bigdigits.py”的基本程序,该程序在python学习教科书中建议,您可以在下面看到这些代码,并弄清楚它是如何工作的。我有一个带有一行数字的“ name.dat”文件,例如12340987与程序文件位于同一文件夹中。

问题是:如何实现此文件,以便将该行数字用作代码的输入数据,最后得到大位数的答案?所有建议都非常感谢。

import sys

Zero  = [" *** ", 
         "*   *", 
         "*   *", 
         "*   *",
         "*   *",
         "*   *",
         " *** "]
One   = [" * ",
         "** ",
         " * ",
         " * ",
         " * ",
         " * ",
         "***"]
Two   = [" *** ",
         "*   *",
         "*  * ",
         "  *  ",
         " *   ",
         "*    ",
         "*****"]
Three = [" *** ",
         "*   *",
         "    *",
         "  ** ",
         "    *",
         "*   *",
         " *** "]
Four  = ["    * ",
         "   ** ",
         "  * * ",
         " *  * ",
         "******",
         "    * ",
         "    * "]
Five  = ["*****",
         "*    ",
         "*    ",
         " *** ",
         "    *",
         "*   *",
         " *** "]
Six   = [" *** ",
         "*   *",
         "*    ",
         "**** ",
         "*   *",
         "*   *",
         " *** "]
Seven = ["*****",
         "    *",
         "   * ",
         "  *  ",
         " *   ",
         "*    ",
         "*    "]
Eight = [" *** ",
         "*   *",
         "*   *",
         " *** ",
         "*   *",
         "*   *",
         " *** "]
Nine  = [" ****",
         "*   *",
         "*   *",
         " ****",
         "    *",
         "    *",
         " *** "]

Digits = [Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine]

try:
    digits = sys.argv[1]
    row = 0
    while row < 7:
        line = ""
        column = 0
        while column < len(digits):
            number = int(digits[column])
            digit = Digits[number]
            line += digit[row].replace('*', digits[column]) + " "
            column += 1
        print(line)
        row += 1
except IndexError:
    print("Usage: bigdigits.py <numbers>")
except ValueError as err:
    print(err, "in", digits)

1 个答案:

答案 0 :(得分:0)

所以,我要问的第一个问题是,您了解这段代码了吗?

如果是,现在基本上需要做的是,每当您要为数字打印一组大数字时查看您在做什么,然后尝试逆转此过程,而是从文件中读取数字:

digits = [None]*10
with open('digits.dat') as fd:
  for line in fd:
    for i in range(10):
        digits[i].append(line[i*5: i*5 + 5])
        # assuming each digit is of width 5, and no space between digits

现在,您已经使用digits文件创建了.dat对象,并且可以从那里继续。