+ 3

(Python Reqex) reading dates and dollar figures from phone text

import re # open a text file f = open("phone.txt", 'r') # extract the file's content content = f.read() # a regular expression pattern to match dates pattern = "\d{2}[/-]\d{2}[/-]\d{4}" dates = re.findall(pattern, content) for date in dates: print(date) f.close() __________________________________ output: 09/01/2021 09/14/2021 09/24/2021 My question is: on the text file I have numbers with $ and dates I was trying to print the number next to the dates that they match on, example of desire output ; Date: 09/01/2021. total: $7.30. sample line going over pass lessons on Character classes and Metacharacters, and groups to get this far on matching dates. Just can't fig out the side-by-side thing on totals next to dates after a day, I am thinking should I be using import panada as pd along with import re to get columns for the data?

2nd Oct 2021, 5:10 PM
Wes
4 Respostas
+ 2
try going over your file line by line instead of calling .findall(), it will make it easier to associate dates and prices together. for line in file: # regex to match date goes here # refex to match price goes here print(f"date: {date}. total: {price}")
2nd Oct 2021, 5:18 PM
Apollo-Roboto
Apollo-Roboto - avatar
0
Sorry I didn't get it! Apollo I did try different. tried for line in file: re,match(total) re,match(dates) for date in dates: print(f"date: {date}. total: {total}") output totals Total:$2 but no date next to or under totals. What I am I missing?
3rd Oct 2021, 1:19 AM
Wes
0
Wes if you use this dates list, you won't be able to properly assign dates to prices assuming your file is as follow: 09/01/2021 $4.24 09/14/2021 $16.50 09/24/2021 $5.00 import re file = open("phone.txt", "r") for line in file: date = re.search("\d{2}[/-]\d{2}[/-]\d{4}", line).group() price = re.search("\$\d*\.\d{2}", line).group() print(f"date: {date}. price: {price}") My regex might not be perfect but I hope it helps. If you absolutely need a list for your dates and price, then you should create objects representing your data and make a list of this object. example with object: import re class MyData: def __init__(self, date, price): self.date = date self.price = price def __str__(self): return f"date: {self.date}. price: {self.price}" file = open("phone.txt", "r") data_list = [] for line in file: date = re.search("\d{2}[/-]\d{2}[/-]\d{4}", line).group() price = re.search("\$\d*\.\d{2}", line).group() data_list.append(MyData(date, price))
3rd Oct 2021, 8:30 PM
Apollo-Roboto
Apollo-Roboto - avatar
0
Mr Apollo Thanks very much, the first example work and working on the code.working on expanding the code. Thanks Wes
6th Oct 2021, 12:24 AM
Wes