0

I am trying to extract certain words from a file using regex in python but I am unable to get it. My original file looks like

List/VB 
[ the/DT flights/NNS ]
from/IN 

and I want the output to be

List VB 
the DT
flights NNS
from IN 

I wrote the following code:

import re

with open("in.txt",'r') as infile, open("out.txt",'w') as outfile: 
    for line in infile:
        if (re.match(r'(?:[\s)?(\w\\\w)',line)):
            outfile.write(line)

2 Answers 2

2

with the sample data you provided:

>>> data = """List/VB 
... [ the/DT flights/NNS ]
... from/IN"""

>>> expr = re.compile("(([\w]+)\/([\w]+))", re.M)
>>> for el in expr.findall(data):
>>>     print el[1], el[2]
List VB
the DT
flights NNS
from IN
Sign up to request clarification or add additional context in comments.

2 Comments

my output is printed as a array, how do i make it a string ?
do you mean you want to convert el[1] and el[2] into a single string? in that case you can do s = "%s %s" % el[1:3]
0
import re

expr = re.compile("(([\w]+)\/([\w]+))", re.M)
fp = open("file_list.txt",'r')
lines = fp.read()
fp.close()
a = expr.findall(lines)
for el in expr.findall(lines):
    print ' '.join(el[1:])

Outputs:

List VB
the DT
flights NNS
from IN

1 Comment

You should formulate your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.