Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I match text that falls within specific parameters in Python?

I have a text file containing my TikTok video browsing data

It looks something like this:

Date: 2022-07-26 00:30:36
Video Link: https://www.tiktokv.com/share/video/7124308827599588614/

Date: 2022-07-26 00:30:31
Video Link: https://www.tiktokv.com/share/video/7124339950736166187/

Date: 2022-07-26 00:29:52
Video Link: https://www.tiktokv.com/share/video/7123899535344028933/

I want to write the Video Link that fall between 2022-07-22 & 2022-07-24 and write them to a new text file.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know how to write data to text files; however, I do not know how I can only match those video links that fall within the dates I have specified.

How can I accomplish this?

>Solution :

One approach would be to read the entire text file into a string, and then use re.findall to find all date/link pairs. Then, filter that list using a comprehension such that only dates within in your range are retained.

inp = """Date: 2022-07-22 00:30:36
Video Link: https://www.tiktokv.com/share/video/7124308827599588614/

Date: 2022-07-24 00:30:31
Video Link: https://www.tiktokv.com/share/video/7124339950736166187/

Date: 2022-07-26 00:29:52
Video Link: https://www.tiktokv.com/share/video/7123899535344028933/"""

matches = re.findall(r'Date: (\d{4}-\d{2}-\d{2}).*?\bVideo Link: (https?://.*?/)\n', inp, flags=re.S)
keep = [x[1] for x in matches if x[0] in ['2022-07-22', '2022-07-23', '2022-07-24']]
print(keep)

# ['https://www.tiktokv.com/share/video/7124308827599588614/',
   'https://www.tiktokv.com/share/video/7124339950736166187/']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading