Python:如何向该excel / xml代码添加逻辑逻辑?

时间:2020-10-22 02:28:32

标签: python excel xml if-statement yattag

我正在为项目使用此当前代码,并希望为某些实例添加逻辑。这是我正在使用的代码,此示例中包含简单的数据/列。

from openpyxl import load_workbook
from yattag import Doc, indent
Path=('/Users/username/Desktop/Popular_Baby_Names.xlsx')

wb = load_workbook(Path)
ws = wb.worksheets[0]
# Create Yattag doc, tag and text objects
doc, tag, text = Doc().tagtext()

xml_header = '<?xml version="1.0" encoding="UTF-8"?>'
xml_schema = '<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
doc.asis(xml_header)
doc.asis(xml_schema)


with tag('Rows'):

    # Use ws.max_row for all rows
    for row in ws.iter_rows(min_row=2, max_row=100, min_col=1, max_col=6):
        row = [cell.value for cell in row]
        with tag("Row"):
            with tag("Year of Birth"):
                text(row[0])
            with tag("Gender"):
                text(row[1])
            with tag("Ethnicity"):
                text(row[2])
            with tag("First Name"):
                text(row[3])
            with tag("Count"):
                text(row[4])  
            with tag("Rank"):
                text(row[5])       
result = indent(
    doc.getvalue(),
    indentation = '    ',
    indent_text = False
)
with open("baby_names.xml", "w") as f:
    f.write(result)

返回哪个

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" dev = "">
<Rows>
    <Row>
        <Year of Birth>2011</Year of Birth>
        <Gender>FEMALE</Gender>
        <Ethnicity>HISPANIC</Ethnicity>
        <First Name>GERALDINE</First Name>
        <Count>13</Count>
        <Rank>75</Rank>
    </Row> 

.
.
.


我正在尝试添加逻辑,以便拾取某些元素。所以我希望(对不起的python代码,主要是r用户)做类似的事情

# Use ws.max_row for all rows
    for row in ws.iter_rows(min_row=2, max_row=100, min_col=1, max_col=6):
        row = [cell.value for cell in row]

   if row[3] == "Geraldine":   (hope that makes sense in psuedocode)
   Print(
        with tag("Row"):
            with tag("Gender"):
                text(row[1])
            with tag("Ethnicity"):
                text(row[2])
            with tag("First Name"):
                text(row[3]))

 if row[3] == "Alex":
  Print(
      with tag("Row"):
            with tag("Gender"):
                text(row[1])
            with tag("Rank"):   #different from previous
                text(row[5])
            with tag("First Name"):
                text(row[3])))

这有意义吗? Kinda想要一个if then语句,以便在某些情况正确的情况下对此进行过滤,并打印出我想要的列对应的行。

我想将其扩展到一个数据集中,如果某列中有某个元素(例如“ referred”或“ notreffered”),则可以选择与之对应的列(例如“ referred date”或“ referral rejected”) 。我相信迭代时的“行”是一个列表,不确定是否如此。

0 个答案:

没有答案