I have tried this using regex, loops and simple functions as well but cannot figure out anything. here are the few codes I have tried.
import re
fp = open("WABA-crash.txt")
re.findall(r"([^.]*?police[^.]*\.)",fp)
For reference, I am placing here a few lines of the WABA-crash.txt
",6810,,,,Crash Description,"Turned right from 38th and Nebraska into a gap in traffic. Car approached from behind and tried to pass too fast and too close, and car’s wing mirror hit my handlebars. Lost control of the bike and crashed on the pavement, hitting my head but sustaining no other injuries. Driver stopped, another witness stopped, both offered aid. Driver offered his name and phone number but I failed to ask for insurance info. Didn’t get witness’s name or phone number. Also, didn’t call the police as I didn’t think I was seriously injured at the time. Only later discovered I had a concussion and went to the ER. Filed a police report after the fact. Now stuck in an insurance fight to cover the medical treatment – I didn’t realize that car insurance is assumed to be the payer of first resort, not sure if my medical insurance will ultimately cover the treatment. Tried to contact the driver on multiple occasions but thus far getting no response. Would prefer not to go the lawyer route, but I’m not sure how else to find out his car insurance info. Any WABA advice welcome!"
11310384,6810,WASHINGTON,DC,20009,Crash Description,"While recovering from a turn, hit a parallel rut in the road and went down."
>Solution :
with open("./WABA-crash.txt", "r") as input:
content = input.read().replace('\n', '')
sentences = list(map(str.strip, content.split(".")))
with open("./resultFile.txt", "w") as output:
for result in sentences:
if ('police' in result or 'Police' in result):
output.write(f'{result}. \n')
There is no need for regex. It might not be the cleanest answer but it works. This is the beauty of Python. When working with files I recommend you to use with open instead of open(). Since this will automatically close the for you. Otherwise you’d need to use the close() method at the end of your file.
Hope this helps you! Enjoy