簡體   English   中英

如何解決這個特殊的“TypeError:Type'NoneType'無法序列化。”錯誤?

[英]How can I solve this particular “TypeError: Type 'NoneType' cannot be serialized.” error?

首先,問題的簡要描述:在無序列表中,我們有許多列表項,每個列表項對應一個“閃卡”

<ul>
    <li>
        <p><span>can you slice columns in a 2d list? </span></p>
        <pre><code class='language-python' lang='python'>queryMatrixTranspose[a-1:b][i] = queryMatrix[i][a-1:b] </code></pre>
        <ul>
            <li>
                <span>No: can&#39;t do this because python doesn&#39;t support multi-axis slicing, only multi-list slicing; see the article </span><a href='http://ilan.schnell-web.net/prog/slicing/' target='_blank' class='url'>http://ilan.schnell-web.net/prog/slicing/</a><span> for more info.</span> 
            </li>
        </ul>
    </li>
</ul>

閃存卡上的答案將始終是位於xpath下的列表項: /html/body/ul/li/ul 我想以這里顯示的格式檢索答案

    <li>
        <span>No: can&#39;t do this because python doesn&#39;t support multi-axis slicing, only multi-list slicing; see the article </span><a href='http://ilan.schnell-web.net/prog/slicing/' target='_blank' class='url'>http://ilan.schnell-web.net/prog/slicing/</a><span> for more info.</span> 
    </li>

flashcard的問題是在提取答案后仍保留在xpath: /html/body/ul/li中的所有內容:

    <li>
        <p><span>can you slice columns in a 2d list? </span></p>
        <pre><code class='language-python' lang='python'>queryMatrixTranspose[a-1:b][i] = queryMatrix[i][a-1:b] </code></pre>
    </li>

對於無序的抽認卡列表中的每個閃卡,我想提取問題和答案列表項的utf-8編碼的html內容。 也就是說,我想同時擁有text和html標簽。


我試圖通過迭代每個閃卡和相應的答案並從父節點閃存卡中刪除子節點答案來解決這個問題。

flashcard_list = []
htmlTree = html.fromstring(htmlString)    
for flashcardTree,answerTree in zip(htmlTree.xpath("/html/body/ul/li"),
 htmlTree.xpath('/html/body/ul/li/ul')):

    flashcard = html.tostring(flashcardTree, 
        pretty_print=True).decode("utf-8")

    answer = html.tostring(answerTree, 
        pretty_print=True).decode("utf-8")

    question = html.tostring(flashcardTree.remove(answerTree), 
        pretty_print=True).decode("utf-8")

    flashcard_list.append((question,answer))

但是,當我嘗試使用flashcardTree.remove(answerTree)刪除答案子節點時,我遇到錯誤, TypeError: Type 'NoneType' cannot be serialized. 我不明白為什么這個函數不會返回; 我想刪除一個節點/html/body/ul/li/ul這是一個有效的子節點/html/body/ul/li

無論你有什么建議,我將不勝感激。 我不會以任何方式依賴我在第一次嘗試時寫的代碼; 我會接受任何答案,其中輸出是(問題,答案)元組的列表,每個閃卡一個。

如果我理解你正在尋找什么,這應該工作:

for flashcardTree,answerTree in zip(htmlTree.xpath("/html/body/ul/li/p/span"),
 htmlTree.xpath('/html/body/ul/li/ul/li/descendant-or-self::*')):

    question = flashcardTree.text
    answer = answerTree.text_content().strip()
    flashcard_list.append((question,answer))

for i in flashcard_list:
    print(i[0],'\n',i[1])

輸出:

你可以在2d列表中切片列嗎?
否:不能這樣做是因為python不支持多軸切片,只支持多列切片; 有關詳細信息,請參閱文章http://ilan.schnell-web.net/prog/slicing/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM