python - Python RegEx 查找接近(之前和/或之后)特定单词的数值
问题描述
我有一个看起来像这样的字符串:
“ 该公寓自 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)```
解决方案
看一下这个:
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)
推荐阅读
- sql - Oracle db:如何获取 current_time?
- events - 如何在 python 对象和 ipywidget 之间进行双向链接
- assembly - x86 XOR 操作码差异
- redis - 将 Kubernetes Pod 中的数据写入主机
- node.js - 如何在 node.js lambda 函数中进行同步 DDB 查询?
- ios - iOS 如何在前台显示本地通知?
- c++ - 为什么 C++ const 引用可以折叠成非 const 引用
- python-3.x - webdriver.Chrome() 不工作
- java - 将整数拆分为单独的部分
- c - 使用 execle 和 putenv 后跟 execl 有什么区别?