python-3.x - 尝试运行简单的 ETL 代码时出现 AttributeError
问题描述
我已经阅读了大量其他线程并且找不到解决方案,所以感谢任何人就如何解决这个问题提出的意见!
完成一门 Python 数据工程课程,这个项目是关于网络抓取的。尝试创建从 XML、CSV 和 JSON 文件中提取数据的函数时,我得到了下面的“AttributeError”。
AttributeError - 1 日志中的回溯(最近一次调用)(“提取阶段开始”)----> 2 提取数据 = 提取() 3 日志(“提取阶段结束”) 4 提取数据
in extract() 29 # 最后,处理所有 xml 文件 30 for xmlFile in glob.glob("*.xml"): ---> 31 extract_data = extract_data.append(xmlExtract(xmlFile), ignore_index=True) 32 33 return提取数据
在 xmlExtract(xmlFile) 15 root = tree.getroot() 16 对于 root 中的人:---> 17 name = person.find("name").text 18 height = float(person.find("height")。文本) 19 重量 = 浮动(person.find("weight").text)
AttributeError:“NoneType”对象没有属性“文本”
这是错误所指的代码片段:
def xmlExtract(xmlFile):
dframe = pddf(columns=["name", "height", "weight"])
tree = ET.parse(xmlFile)
root = tree.getroot()
for person in root:
name = person.find("name").text
height = float(person.find("height").text)
weight = float(person.find("weight").text)
dframe = dframe.append({"name":name, "height":height, "weight":weight}, ignore_index=True)
return dframe
感谢任何关于从哪里开始的指示。
PS 'pdf' 是从 pandas 独特导入的 pandas.dataframe - from pandas import DataFrame as pddf
- 因为我遇到了错误import pandas as pd
,然后使用 pd.dataframe。
解决方案
错误很明显:
AttributeError: 'NoneType' object has no attribute 'text'
一些电话.find
正在返回None
。您必须None
在调用.text
.
def xmlExtract(xmlFile):
dframe = pddf(columns=["name", "height", "weight"])
tree = ET.parse(xmlFile)
root = tree.getroot()
for person in root:
name = person.find("name").text if person.find("name") else None
height = float(person.find("height").text) if person.find("height") else None
weight = float(person.find("weight").text) if person.find("weight") else None
dframe = dframe.append({"name": name, "height": height, "weight": weight}, ignore_index=True)
return dframe
这段代码不是最好的。这只是一个例子。
推荐阅读
- c++ - XCode 上的 OpenCV4 — 未找到 opencv2/core.hpp
- vb.net - 如何在表单上显示各种字符
- file - 修复小批处理文件
- php - 使用 Laravel 7 和 Mysql 创建应用测验
- typescript - *ngFor 导致 charJs 图表闪烁(即使使用 .destroy())
- python - 从文件夹内的文件名中删除某些字符串
- c - 如何只打印出十六进制数的最后两位
- macos - macOS High Sierra - 找不到颤振命令
- maven - 带有 @PrepareForTest 的 Powermock Mockito 在 JaCoCo maven 插件中没有提供正确的覆盖范围。有什么选择吗?
- python - 需要帮助理解 Tensorflow 中的编码器-解码器代码