读取已拆分的行上的两个Y

2024-05-16 00:10:58 发布

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

我在逗号处把两行分开(去掉) 我只剩下列宁斯一家的名字,乔治,Y,Y,但因为它被分开了,我不能把Y读作同一行的一部分。我知道这很简单,但我非常困惑(也是从文件中读取)

empFile = "Employee.txt"
confFile = "confpacks.txt"

confFile = open("confpacks.txt", "r")
packsread = confFile.readlines()

readFile = open("Employee.txt", "r")
records = readFile.readlines()

    for line in records:
      line = line[:-1]
      fields = line.split(",")

      for field in fields:
        print(field, end=" , ")



        if field == "Y":
          print("Only attended one day therefore recieves " + packsread[0])

预期产量

如果有名字和两个Y那么

John, Steward, Y , Y, attended both days.

如果有名字和一个Y那么

John, Steward,Y attended one day

如果根本没有Y

John, Steward, did not attend any days

Tags: txtfieldlineemployeeopen名字johnrecords
1条回答
网友
1楼 · 发布于 2024-05-16 00:10:58

您可以在行尾计数Y,并根据计数器添加消息:

for line in file:
    line = line.strip()
    fields = line.split(",")

    count = 0
    for v in reversed(fields):
        if v == 'Y':
            count += 1
        else:
            break

    print(', '.join(fields), end=', ')

    if not count:
        print('did not attend any days')
    elif count == 1:
        print('attended one day')
    else:
        print('attended both days')

相关问题 更多 >