Untitled

 avatar
unknown
plain_text
3 years ago
1.9 kB
5
Indexable
The overall code for the given question is :
import re

# regex for ip-address 
ip_pattern = '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'

# regex for date 
date_pattern = '(\d{2}\/\w{3}\/\d{4})'

# stroing the output string
output =[]

with open('log_task1.txt') as f:
  string = f.readlines()
  
  for s in string:
    #finding the ip from each line
    i = re.findall(ip_pattern,s)

    #finding date from each line
    d = re.findall(date_pattern,s)
    d = re.sub("/","-",d[0])

    # appending output to the list 
    output.append(str(i[0]) +" " +str(d))

with open(r'output_task1.txt', 'w') as fp:
    for item in output:
        # write each item on a new line
        fp.write("%s\n" % item)
    


Explanationfor step 1
This is the overall code.
Step 2/4
Regex for given code:
# regex for ip-address 
ip_pattern = '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'

# regex for date 
date_pattern = '(\d{2}\/\w{3}\/\d{4})'

Explanationfor step 2
These are the regex for IP-address and Date.
Step 3/4
reading "log_task1.txt" file:

with open('log_task1.txt') as f:
  string = f.readlines()
  
  for s in string:
    #finding the ip from each line
    i = re.findall(ip_pattern,s)

    #finding date from each line
    d = re.findall(date_pattern,s)

    #replacing "/" with "-"
    d = re.sub("/","-",d[0])

    # appending output to the list 
    output.append(str(i[0]) +" " +str(d))

Explanationfor step 3
Here, the regex are matched for ip-address and date.
Finally these are appended to output list with concatinating. 
Step 4/4
Writing the output to the "output_task.txt":


with open(r'output_task1.txt', 'w') as fp:
    for item in output:
        # write each item on a new line
        fp.write("%s\n" % item)
    

Explanationfor step 4
All the items of output list is written to the "output_task1.txt" file.
Final answer
This is all code for the given question.

Kindly Upvote. 
Editor is loading...