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

Time:07-29

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.

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?

CodePudding user response:

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/']
  • Related