將 XML 數據解析為 Pandas python

我想將我的 XML 文件轉換為數據框熊貓我試過這段代碼

import pandas as pd
from bs4 import BeautifulSoup

soup = BeautifulSoup(open("C:/Users/user/Desktop/essai/dataXml.xml", "r"),"xml")

d = {}
for tag in soup.RECORDING.find_all(recursive=False):
    
    d[tag.name] = tag.get_text(strip=True)
df = pd.DataFrame([d])
print(df)

這是我的 XML 數據的一部分


<?xml version="1.0" encoding="utf-8"?>
<sentences>
    <sentence>
        <text>We went again and sat at the bar this time, I had 5 pints of guinness and not one buy-back, I ordered a basket of onion rings and there were about 5 in the basket, the rest was filled with crumbs, the chili was not even edible.</text>
        <aspectCategories>
            <aspectCategory category="place" polarity="neutral"/>
            <aspectCategory category="food" polarity="negative"/>
        </aspectCategories>
    </sentence>
</sentences>`

我收到了這個錯誤

for tag in soup.RECORDING.find_all(recursive=False):
AttributeError: 'NoneType' object has no attribute 'find_all'

我該如何解決?

提前謝謝你

編輯:替換soup.RECORDING.find_allsoup.find_all修復了錯誤,但我仍然沒有得到我想要的

我想要這樣的東西 在此處輸入圖片說明

用戶17242583

試試這個代碼:

d = {
    'text': [],
    'aspect': [],
    'polarity': []
}

for sentence in soup.find_all('sentence'):
    text = sentence.find('text').text
    for ac in sentence.find_all('aspectCategory'):
        d['text'].append(text)
        d['aspect'].append(ac.get('category'))
        d['polarity'].append(ac.get('category'))
    
df = pd.DataFrame(d)

輸出:

>>> df
                                                text aspect polarity
0  We went again and sat at the bar this time, I ...  place    place
1  We went again and sat at the bar this time, I ...   food     food

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python 將浮點數列表轉換為 Pandas 數據幀溢出

使用 python 和 Pandas 將多數組 json 數據轉換為扁平數據框

在python中如何將字符串列表轉換為pandas數據框

將列表類型字典轉換為 Pandas 數據框 - python

嘗試在 Python-Pandas 中將數據幀轉換為字典

Python:將嵌套的 Dictionary 對象轉換為 Pandas 數據幀

將python列表轉換為pandas數據框的問題

Pandas Python 將記錄中的列表數據轉換為迭代行

Python Pandas 數據框將 col 的值重塑為新的 col

將 Json 轉換為 Pandas 數據框

將 txt 文件轉換為 Pandas 數據框

Pandas 數據框將行轉換為列

Pandas:將數據框轉換為嵌套字典

Python FTP:從 FTP 讀取 .xlsx 作為 Pandas 數據幀而不將 .xlsx 寫入磁盤

如何使用 Pandas 數據框將 R 代碼語法轉換為 Python 語法?

如何在python中使用pandas將多項選擇題轉換為可讀數據?

python pandas將唯一行轉換為具有各自數據的新列

根據列的值將 Pandas 數據幀拆分為多個數據幀

在 Python 中將系列轉換為數據框

Python:根據值範圍將數據幀拆分為數據幀字典

將 Pandas 數據幀重組為更簡潔的數據幀

將一組數據(URLS)放入一個空的數據幀 Python Pandas

Python - Pandas - 將列名複製到新數據框而不帶數據

將python中的無序數據更改為有序數據框

Pandas 為 pyspark 數據框應用函數替代(想要將整數數據類型列轉換為列表數據類型)

Pandas:將一列數據集從字符串更改為整數

如何將 Pandas 數據幀轉換為 NumPy 數組

需要從列中獲取特定數據並使用 Python 和 Pandas 將它們轉置為行

pandas 替換命令無法將分類數據更改為數值數據