从已删除数据列表中的每个单词中选择第一个字符

时间:2017-01-20 14:20:03

标签: python python-3.x beautifulsoup

我一直在努力缩减使用bs4删除的一些数据。

我正在尝试缩写输出:

import urllib.request
from bs4 import BeautifulSoup

url = "http://www.bbc.co.uk/weather/en/2644037/?day1"
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page, "html5lib")
weekWeather = soup.find('div', {'class':'daily-window'})
wD = [x.text for x in weekWeather.findAll('span', {'class':'description blq-hide'})]

输出是一个列表......

['South South Westerly', 'South Westerly', 'Southerly', 'Southerly', 'Southerly']

我想缩写为['SSW', 'SW', 'S', 'S', 'S']

我的第一个计划是使用split(),然后选择所有upper(),然后我尝试使用map迭代每个单词,并选择第一个字符,但我只收到第一个字母每个元素(即[S, S, S, S, S]

我感觉这是因为数据的返回方式?

任何指针都会很棒,谢谢。

1 个答案:

答案 0 :(得分:0)

在最简单的形式中,您可以通过.split() 按空格分割并获取每个单词的第一个字符:

["".join([item[0] for item in x.text.split()])
 for x in weekWeather.select('span.description.blq-hide')]

会返回:

['SSW', 'SW', 'S', 'S', 'S']
相关问题