Python 如何获得最近的标签
我有一个包含以下数据的xml文件Python 如何获得最近的标签,python,python-2.7,beautifulsoup,Python,Python 2.7,Beautifulsoup,我有一个包含以下数据的xml文件 <year>2013</year> <youSaveSpend>2500</youSaveSpend> <yourMpgVehicle> <avgMpg>32.261695541</avgMpg> <cityPercent>43</cityPercent> <highwayPercent>57</highwayPercent> &l
<year>2013</year>
<youSaveSpend>2500</youSaveSpend>
<yourMpgVehicle>
<avgMpg>32.261695541</avgMpg>
<cityPercent>43</cityPercent>
<highwayPercent>57</highwayPercent>
</yourMpgVehicle>
<year>2013</year>
<youSaveSpend>3000</youSaveSpend>
<yourMpgVehicle>
<avgMpg>33.383275416</avgMpg>
<cityPercent>49</cityPercent>
<highwayPercent>51</highwayPercent>
</yourMpgVehicle>
<year>2012</year>
<youSaveSpend>2500</youSaveSpend>
<yourMpgVehicle>
<avgMpg>36.210640188</avgMpg>
<cityPercent>32</cityPercent>
<highwayPercent>68</highwayPercent>
</yourMpgVehicle>
但是字典不接受重复项:S因为我们知道元素将彼此靠近,所以我们可以通过搜索
下一个兄弟姐妹来到达:
from bs4 import BeautifulSoup
with open('mpg.xml') as f:
contents=f.read()
mpgs = BeautifulSoup(contents)
def find_nearest_vehicle(elem):
for sibling in elem.next_siblings:
if sibling.name == 'yourmpgvehicle':
return sibling
def find_avg_mpg(elem):
for child in elem.children:
if child.name == 'avgmpg':
return child
year_2013 = [year for year in mpgs.find_all('year')
if year.string == '2013']
avgmpg = [find_avg_mpg(find_nearest_vehicle(elem)).string
for elem in year_2013]
print(avgmpg)
当我在你的文件上运行此命令时,我得到:
$ python3 mpg.py
['32.261695541', '33.383275416']
就快到了,你可以把最后一行改成:
result = [avgMpg for year, avgMpg in zip(listOfYears, listOfAvgMpg) if year=='2013']
请注意,2013
是一个字符串,而不是整数
或者,对于缩短的总体代码(我将年份转换为int
s,将avgMpg
s转换为float
s):
结果:
[32.261695541, 33.383275416]
[32.261695541, 33.383275416]
请包括您当前的努力,我们将帮助您修复它。但是,这不是一个代码编写服务。你被卡在哪里了?为什么您对使用本机python库不感兴趣呢?那么为什么不首先,如果希望将标记与后续标记匹配以获得它们之间的关系,那么这个XML就不是严格格式良好的。元素应该位于另一个标记内。其次,你不能使用dict,对吗?只需对这些值进行迭代?为了扩展几乎所有的解决方案,您实际上可以这样做:[avgMpg for year,avgMpg in zip(listOfYears,listOfAvgMpg),如果year==2013]
来获得您想要的内容。您应该获得32.261
和33.383
,对吗,你可以使用.string
而不是next\u元素
我认为最好在中搜索名为avgMpg
的标记。next\u sides
而不是(elem,4)
上的硬编码,因为空格可能会改变。是的,我也只是改变了它来进行搜索。我将指出,像您一样,这样解析XML并不是很理想。您应该让元素按照它们的分组标记进行分组,而不是像@user1607549那样在物理上彼此靠近。看起来不错。只是你不需要搜索来找到avgmpg
,你只需要做find\u nearest\u vehicle(elem).avgmpg
。
from bs4 import BeautifulSoup as BS
soup = BS(string, 'lxml')
listOfYears = [int(el.string) for el in soup.find_all('year')]
listOfAvgMpg = [float(el.string) for el in soup.find_all('avgmpg')]
result = [avgMpg for year, avgMpg in zip(listOfYears, listOfAvgMpg) if year==2013]
print result
[32.261695541, 33.383275416]