从还提到卧室数量的字符串中提取平方米的最佳方法是什么? [英] What would be the best way to extract square meters from a string that also mentions the amount of bedrooms?

查看:92
本文介绍了从还提到卧室数量的字符串中提取平方米的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提取:

<div class="xl-surface-ch"> 
                            &nbsp;84 m²  &nbsp;&nbsp;&nbsp;2 bed.  
                        </div>

来自链接,问题是,我只需要该字符串中的"84"(有时也会超过2或3位数字).

from link the problem is, I only need the "84" in this string (they sometimes go over 2 or 3 digits as well).

增加的困难是有时没有提到平方米,这看起来像这样:

Added difficulty is that sometimes the square meters are not mentioned, which looks like this:

<div class="xl-surface-ch"> 
                             &nbsp;&nbsp;&nbsp;2 bed.  
                        </div>

在这种情况下,我需要返回0

and in that case I'd need to 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)

但是,这似乎不起作用,也根本不是我为上述最终结果所需要的. 这是我通过代码得到的结果:

But this doesn't seem to work and won't be at all what I need for the end result as stated above. Here's the result I'm getting with my code:

[['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语句?我现在无论如何都要尝试.

Would be really interested in what kinds of solution you guys cook up because I honestly think there isn't really a solution, especially since you sometimes have buildings without the sqm... maybe with an if statement? I'm going to try that right now anyhow.

先谢谢您!

推荐答案

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 

这篇关于从还提到卧室数量的字符串中提取平方米的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆