提问人:Felix Huber 提问时间:5/9/2021 更新时间:5/9/2021 访问量:78
Python RegEx 查找接近(之前和/或后)特定单词的数字值
Python RegEx to find number value close to (before and/or behind) specific words
问:
我有一个字符串,看起来像这样:
“ 自 2021 年以来,该公寓已出租给一名学生。月租金为850欧元,额外费用为水电费(150欧元)。
我正在寻找与“租金”和“欧元”非常接近的数值(例如在 20 个字符以内)。
我不想得到“2021”,也不想得到“150”——我想得到“850”。
目前我正在使用此代码,但最终我得到了“2021”。你可以帮我吗?
提前非常感谢! 费利克斯
txt = "The apartment is rented out to a student since 2021. The monthly rent is 850 Euro. Additional costs are utilities (150 Euro)."
txt = ("".join(txt)).strip()
m = re.search(r'(?:((?i:rent)|JNKM)[\w\€\:\(\)\.\!\?\-\\,\ ]{0,40}(\d+[\,\.]?\d*)|(?:(\d+[\,\.]?\d*)[\w\€\:\(\)\.\!\?\-\\,\ ]{0,40}((?i:rent)|JNKM)))',"".join(txt))
txtrent = m.group().replace(".","").replace(",",".")
txtrent = re.findall(r"-?\d+[\,\.]?\d*", txtrent )
zustand = txtrent
print(zustand)```
答:
0赞
Asir Shahriar Roudra
5/9/2021
#1
看看这个:
txt = "The apartment is rented out to a student since 2021. The monthly rent is 850 Euro. Additional costs are utilities (150 Euro)."
txt = txt.replace('.', '')
pattern = '\s'
result = re.split(pattern, txt)
txt = result[result.index('rent'): result.index('Euro')+1]
for i in txt:
if i.isdigit():
print(i)
评论
euro
\b(?:(?i:rent)|JNKM)\b\D{0,40}(\d+(?:[,.]\d+)?)\D{0,40}\b(?i:Euro)\b