【问题标题】:Print multiple times in python?在python中多次打印?
【发布时间】:2021-02-12 22:29:52
【问题描述】:
    from simplified_scrapy import SimplifiedDoc, utils
    #simplified_scrapy is framework for extrcting data
    xml = utils.getFileContent('check_in.xml')
    doc = SimplifiedDoc(xml)
    #SimplifiedDoc is a library for parsing data such as HTML and XML
    
    nodes = doc.select('air:EDS_AirCheckInRQ').children
    print (nodes.tag)
    
    for x in nodes:
        print((doc.select('air:EDS_AirCheckInRQ')['Version']),(doc.select('com:Source')))
              
    
    Here is my output:-
    4.000 {'tag': 'com:Source', 'AirlineVendorID': 'CM'}
    4.000 {'tag': 'com:Source', 'AirlineVendorID': 'CM'}
    4.000 {'tag': 'com:Source', 'AirlineVendorID': 'CM'}
    4.000 {'tag': 'com:Source', 'AirlineVendorID': 'CM'}
    4.000 {'tag': 'com:Source', 'AirlineVendorID': 'CM'}
    4.000 {'tag': 'com:Source', 'AirlineVendorID': 'CM'}

这是我的 python 代码,我只想在其中打印一次,但是当我运行它时,它会给出多次打印的输出。我只想打印一次。 谁能帮我解释为什么这个打印多次而不是一次?

【问题讨论】:

    标签: python python-3.x xml xml-parsing


    【解决方案1】:

    就像 Adamantoisetortoise 所说的那样,您正在循环打印。 摆脱这个:

    for x in nodes:
            print((doc.select('air:EDS_AirCheckInRQ')['Version']),(doc.select('com:Source')))
    

    据我了解,您正在尝试从节点中提取一些信息 你可以试试这个:

    for x in nodes:
            print((x.select('air:EDS_AirCheckInRQ')['Version']),(x.select('com:Source')))
    

    但这可能行不通,因为我不知道您使用的是什么数据。

    【讨论】:

    • 以上循环不起作用,抛出错误“NoneType”对象不可下标。这里我尝试解析 SOAP XML 并从中提取信息。
    • 正如我所说,我不知道您正在处理什么数据。因此,我不能说肯定...
    • 如果可能没有值,这样就不会报错:(x.select('air:EDS_AirCheckInRQ>Version()')
    【解决方案2】:

    如果您在for x in nodes: 中有print(),它将为nodes 中的每个x 打印。 只需删除您的 for 循环,您甚至没有在循环中使用 x

    【讨论】:

    • 谢谢,我明白了。你知道如何在这里使用循环,因为我有很多参数要打印吗?
    • 您的 for 循环必须以某种方式涉及“x”,但根据目前的信息,我只能建议像 @Benjamin Philip 已经建议的那样用“x”替换“doc”。跨度>
    猜你喜欢
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2021-04-03
    • 1970-01-01
    相关资源
    最近更新 更多