[英]How to find specific text with it's correspondence value from a text input using Regex and Python?
我有一些文本輸入,我想從文本中提取一些信息。 為此,我正在嘗試使用正則表達式並且能夠做到這一點,除了兩個領域 - 租金和轉讓。
輸入文本如下-
my_str = "19 Aug standing order rent Apolo Housing Assoc. 500.00 50.00
20 Aug transfer from John wick saving a/c 200.00 130.90"
現在我想提取 rent like- rent 500.00
和 transfer as transfer 200.00
但不知何故只有“rent”和“transfer”關鍵字被提取。
下面是我在 Python 中的相同代碼-
import re
find_rent = re.search(r"(rent)+([0-9,.]*)", my_str)
found = find_rent.group()
print(found)
使用上面的代碼,只提取“租金”而不是“租金 500.00”。 我也使用類似的代碼進行傳輸。
請指導我在這里做錯了什么。
您可以使用
\b(transfer|rent)\D+(\d+(?:[,.]\d+)*)
請參閱正則表達式演示。 詳情:
\b
- 單詞邊界(transfer|rent)
- 第 1 組: transfer
或rent
詞\D+
- 一個或多個非數字(\d+(?:[,.]\d+)*)
- 第 2 組:一位或多位數字,然后零次或多次出現逗號/句點和一位或多位數字請參閱Python 演示:
import re
s = '19 Aug standing order rent Apolo Housing Assoc. 500.00 50.00\n20 Aug transfer from John wick saving a/c 200.00 130.90'
rx = r'\b(transfer|rent)\D+(\d+(?:[,.]\d+)*)'
for m in re.finditer(rx, s):
print(f'{m.group(1)} {m.group(2)}')
Output:
rent 500.00
transfer 200.00
對於單個術語搜索,您可以使用
import re
s = '19 Aug standing order rent Apolo Housing Assoc. 500.00 50.00\n20 Aug transfer from John wick saving a/c 200.00 130.90'
w = 'rent'
rx = fr'\b{w}\D+(\d+(?:[,.]\d+)*)'
m = re.search(rx, s)
if m:
print(f'{w} {m.group(1)}')
請參閱此 Python 演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.