通读文本文件并添加子字符串(python)

2024-09-20 06:33:28 发布

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

我正在处理这个文本文件

Widget1
partA 2
partB 8
partC 4

Widget2
partD 30
partB 92

Widget3
partA 1
partB 1000
partC 500
partD 450

Widget4
partA 49
partC 100
partD 97

Widget5
partA 10
partD 20

我想为每个小部件添加所有部件数量,因此输出将是 “小部件1需要14个部件 小部件2需要122个部件”等。我无法跟踪到各自小部件的数量总和。thx提前。这是我到目前为止得到的

widgetfile = open("widgets.txt", "r", encoding="utf-8")
i=0
parttotal=0.0
quantities=[]
widgetdict={}
for line in widgetfile:
            if "Widget" in line:
                widget.append(line)
            if "part" in line:
                substring=line.split(" ")
                quantities.append(substring[1])

Tags: in数量if部件linesubstring文本文件append
1条回答
网友
1楼 · 发布于 2024-09-20 06:33:28

现在,您正在将所有数量添加到一个大列表中,然后无法区分哪些数量属于哪个小部件。相反,您可以动态地添加这些值,当您运行到下一个“Widget”行(或文件末尾)时,您就知道您已经完成了该Widget

此外,我建议在完成后使用with自动关闭文件:

with open("widgets.txt", "r", encoding="utf-8") as widgetfile:
    current_total = 0
    current_widget = None # We don't have a widget yet
    for line in widgetfile:
        if "Widget" in line:
            # Output the current widget here, if there is one
            if current_widget != None:
                print("{} needs {} parts".format(current_widget, current_total))
            # Now store the new widget's name and reset the count
            current_widget = line
            current_total = 0
        elif "part" in line:
            # Take the second part of the line, convert it to a number
            # and add it to the current total
            current_total += int(line.split()[1])
    # The loop is now done, but we haven't printed the last widget yet
    if current_widget != None:
        print("{} needs {} parts".format(current_widget, current_total))

请注意,我们如何在完成单个小部件后立即重置总计数,以及我们如何不必跟踪单个数量(或在多个小部件的任何点)

相关问题 更多 >