1

I have a file which contain

[[ abstraction, verb.cognition:abstract,+ ]] 

I want to remove the square bracket and want to keep the word abstraction from this bracket. So the output should be -

abstraction

I have tried -

import re

with open('test.txt','r') as f:
    for line in f:
        rx = re.compile(r'\[[^][]*]')  string
        while rx.search(line):
            line = rx.sub('',line)                     
            s = line.strip()
            print(s)

which shows [] only square bracket.Is there ay way to do this? please help .

1
  • 2
    If the format doesn't change, simple string formatting would do: s.split(',')[0].lstrip('[ '). Apr 24, 2018 at 6:07

3 Answers 3

1

using re.search

Ex:

s = "[[ abstraction, verb.cognition:abstract,+ ]]"
m = re.search("\[\[(.*?)\,.*", s)
if m:
    print(m.group(1))

Output:

 abstraction
2
  • It works but In my file there are more lines like - entity , [[ abstraction, verb.cognition:abstract,+ ]] , physical_entity . I also want to print these lines entity abstraction physical_entity . I have tried your code,it shows abstraction which is correct . But when I want to print others line how can i do that?
    – jan
    Apr 24, 2018 at 7:43
  • @jahan. That would mean a totally different requirement and regex.
    – Rakesh
    Apr 24, 2018 at 7:50
1

You don't even need to worry about the brackets, if your file only contains that, you only need to match the first word.

import re
t = "[[ abstraction, verb.cognition:abstract,+ ]] "

match = re.search(r"\b([^,]+)\b", t)
# prints False when no match is found
print(match is not None and match.group(0))
# abstraction
1

You can try this too,

line="""[[ abstraction, verb.cognition:abstract,+ ]] rewq [[ abs, verb.cognition:abstract,+ ]] fdsaf [[ abstraction, verb.cfdsa,+ ]] """
rx = re.compile(r'\[\[[^][]*]]')
line = rx.sub(lambda m: '' if m.group(0).find("abstraction")== -1 else "abstraction", line)                     
s = line.strip()
print(s)

Output is

abstraction rewq  fdsaf abstraction

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.