读文件并打印输出

2024-05-08 04:39:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读一个文件,输出应该像下面的那个,忽略了实际的表,我的小时,分钟和秒的值和钱一样,应该是四舍五入到分钟来计算的;我已经尝试了很多方法来解决这个问题,这是我最后的选择。在

+--------------+------------------------------+---+---------+--------+
| Phone number | Name                         | # |Duration | Due    |
+--------------+------------------------------+---+---------+--------


|(780) 123 4567|Ameneh Gholipour Shahraki     |384|55h07m53s|$ 876.97|**
|(780) 123 6789|Stuart Johnson                |132|17h53m19s|$ 288.81|
|(780) 321 4567|Md Toukir Imam                |363|49h52m12s|$ 827.48|++
|(780) 432 1098|Hamman Samuel                 |112|16h05m09s|$ 259.66|
|(780) 492 2860|Osmar Zaiane                  |502|69h27m48s|$1160.52|**
|(780) 789 0123|Elham Ahmadi                  |259|35h56m10s|$ 596.94|
|(780) 876 5432|Amir Hossein Faghih Dinevari  |129|17h22m32s|$ 288.56|
|(780) 890 7654|Weifeng Chen                  |245|33h48m46s|$ 539.41|
|(780) 987 6543|Farrukh Ahmed                 |374|52h50m11s|$ 883.72|**
+--------------+------------------------------+---+---------+--------+
| Total dues   |                                          $   5722.07|
+--------------+-----------------------------------------------------+

这是我的代码,我在time()和due()函数中遇到的问题最多

^{pr2}$

这是指向我在pastebin中读取的文件的链接:http://pastebin.com/RSMnXDtq

第一列是电话号码。此号码的格式必须为(999)999 9999。在

第二列是名称,宽度必须为30个字符。在

第三列是有关电话发出的呼叫数。应该是3位数。在

第四列是来自所述电话的总持续时间。此持续时间的格式如下:99h99m99s,分、秒。如果分钟和秒小于10,则前缀应为0。在

第五列是根据每次通话的费率计算的话费。请注意,为了使用每分钟的速率,每次呼叫的持续时间应四舍五入到分钟。该金额应打印7位小数点后2位。在


Tags: 文件方法namenumber格式phonedue持续时间
1条回答
网友
1楼 · 发布于 2024-05-08 04:39:15

以下是使用熊猫的解决方案:

from pandas import np, read_csv

#
# Load and process call data
#

def get_data(calls_fname, custs_fname):
    # load call data
    calls = read_csv(
        calls_fname,
        sep    = ";",
        names  = ["session", "phone", "to", "seconds", "rate"],
        header = None
    )    
    # calculate cost per call (time rounded up to the next minute)
    calls["cost"] = np.ceil(calls["seconds"] / 60.) * calls["rate"]
    # add a call-count column
    #   (I think there is a better way to do this using np.size in
    #   the .groupby, but I haven't been able to figure it out)
    calls["count"] = 1
    # find per-cust totals
    calls = calls.groupby(["phone"]).agg({"seconds":np.sum, "cost":np.sum, "count":np.sum})
    # load customer data
    custs = read_csv(
        custs_fname,
        sep       = ";",
        names     = ["phone", "name"],
        header    = None,
        index_col = 0   # index by phone number
    )
    # join to find customer name
    return calls.join(custs, sort=False).reset_index()

#
# output formatting functions
#

def phone_str(i):
    """
    Convert int 1234567890 to str "(123) 456 7890"
    """
    s = str(i).zfill(10)
    return "({}) {} {}".format(s[0:3], s[3:6], s[6:10])

def time_str(i):
    """
    Convert int 3662 to str " 1h01m02s"
    """
    m, s = divmod(i, 60)
    h, m = divmod(m, 60)
    return "{:>2d}h{:02d}m{:02d}s".format(h, m, s)

def make_table(totals):
    header = (
        "+       +               + -+    -+    +\n"
        "| Phone number | Name                         | # |Duration | Due    |\n"
        "+       +               + -+    -+    +\n"
    )
    rows = [
        "|{}|{:<30}|{:>3d}|{}|${:7.2f}|\n"
        .format(
            phone_str(row["phone"  ]),
                      row["name"   ],
                      row["count"  ],
            time_str (row["seconds"]),
                      row["cost"   ]
        )
        for i,row in totals.iterrows()
    ]
    total_dues = np.sum(totals["cost"])
    footer = (
        "+       +               + -+    -+    +\n"
        "| Total dues   |                                          ${:10.2f}|\n"
        "+       +                          -+"
        .format(total_dues)
    )
    return header + "".join(rows) + footer

def main():
    totals = get_data("calls.txt", "customers.txt")
    print(make_table(totals))

if __name__ == "__main__":
    main()

将pastebin链接中的数据用作calls.txt,并将以下内容用作customers.txt

^{pr2}$

它产生了

+       +               + -+    -+    +
| Phone number | Name                         | # |Duration | Due    |
+       +               + -+    -+    +
|(780) 123 4567|Ameneh Gholipour Shahraki     |384|55h07m53s|$ 876.97|
|(780) 123 6789|Stuart Johnson                |132|17h53m19s|$ 288.81|
|(780) 321 4567|Md Toukir Imam                |363|49h52m12s|$ 827.48|
|(780) 432 1098|Hamman Samuel                 |112|16h05m09s|$ 259.66|
|(780) 492 2860|Osmar Zaiane                  |502|69h27m48s|$1160.52|
|(780) 789 0123|Elham Ahmadi                  |259|35h56m10s|$ 596.94|
|(780) 876 5432|Amir Hossein Faghih Dinevari  |129|17h22m32s|$ 288.56|
|(780) 890 7654|Weifeng Chen                  |245|33h48m46s|$ 539.41|
|(780) 987 6543|Farrukh Ahmed                 |374|52h50m11s|$ 883.72|
+       +               + -+    -+    +
| Total dues   |                                          $   5722.07|
+       +                          -+

相关问题 更多 >