从还提到卧室数量的字符串中提取平方米的最佳方法是什么?
What would be the best way to extract square meters from a string that also mentions the amount of bedrooms?
我正在尝试提取:
<div class="xl-surface-ch">
84 m² 2 bed.
</div>
来自 link 问题是,我只需要这个字符串中的“84”(它们有时也会超过 2 或 3 个数字)。
增加的困难是有时没有提到平方米,看起来像这样:
<div class="xl-surface-ch">
2 bed.
</div>
在这种情况下,我需要 return a 0
我最好的尝试是:
sqm = []
for item in soup.findAll('div', attrs={'class': 'xl-surface-ch'}):
item = item.contents[0].strip()[0:4]
item_clean = re.findall("[0-9]{2,4}", item)
sqm.append(item_clean)
print(sqm)
但这似乎不起作用,而且根本不是我对上述最终结果所需要的。
这是我的代码得到的结果:
[['84'], ['70'], ['80'], ['32'], ['149'], ['22'], ['75'], ['30'], ['23'], ['104'], [], ['95'], ['129'], ['26'], ['55'], ['26'], ['25'], ['28'], ['33'], ['210'], ['37'], ['69'], ['36'], ['19'], ['119'], ['20'], ['20'], ['129'], ['154'], ['25']]
真的很想知道你们想出了什么样的解决方案,因为老实说,我认为没有真正的解决方案,尤其是因为您有时拥有没有 sqm 的建筑物...也许带有 if 语句?无论如何,我现在就去试试。
提前致谢!
import requests
from bs4 import BeautifulSoup
r = requests.get(
'https://www.immoweb.be/en/search/apartment/for-sale/leuven/3000')
soup = BeautifulSoup(r.text, 'html.parser')
for item in soup.findAll('div', attrs={'class': 'xl-surface-ch'}):
item = item.text.strip()
if 'm²' in item:
print(item[0:item.find('m')])
else:
item = 0
print(item)
输出:
84
70
80
32
149
22
75
30
23
104
0
95
129
26
55
26
25
28
33
210
37
69
36
19
119
20
20
129
154
25
我正在尝试提取:
<div class="xl-surface-ch">
84 m² 2 bed.
</div>
来自 link 问题是,我只需要这个字符串中的“84”(它们有时也会超过 2 或 3 个数字)。
增加的困难是有时没有提到平方米,看起来像这样:
<div class="xl-surface-ch">
2 bed.
</div>
在这种情况下,我需要 return a 0
我最好的尝试是:
sqm = []
for item in soup.findAll('div', attrs={'class': 'xl-surface-ch'}):
item = item.contents[0].strip()[0:4]
item_clean = re.findall("[0-9]{2,4}", item)
sqm.append(item_clean)
print(sqm)
但这似乎不起作用,而且根本不是我对上述最终结果所需要的。 这是我的代码得到的结果:
[['84'], ['70'], ['80'], ['32'], ['149'], ['22'], ['75'], ['30'], ['23'], ['104'], [], ['95'], ['129'], ['26'], ['55'], ['26'], ['25'], ['28'], ['33'], ['210'], ['37'], ['69'], ['36'], ['19'], ['119'], ['20'], ['20'], ['129'], ['154'], ['25']]
真的很想知道你们想出了什么样的解决方案,因为老实说,我认为没有真正的解决方案,尤其是因为您有时拥有没有 sqm 的建筑物...也许带有 if 语句?无论如何,我现在就去试试。
提前致谢!
import requests
from bs4 import BeautifulSoup
r = requests.get(
'https://www.immoweb.be/en/search/apartment/for-sale/leuven/3000')
soup = BeautifulSoup(r.text, 'html.parser')
for item in soup.findAll('div', attrs={'class': 'xl-surface-ch'}):
item = item.text.strip()
if 'm²' in item:
print(item[0:item.find('m')])
else:
item = 0
print(item)
输出:
84
70
80
32
149
22
75
30
23
104
0
95
129
26
55
26
25
28
33
210
37
69
36
19
119
20
20
129
154
25