How to remove brackets from text file in Python ?
Sometimes it becomes tough to remove brackets from the text file which is unnecessary to us. Hence, python can do this for us. In python, we can remove brackets with the help of regular expressions.
Syntax:
# import re module for using regular expression
import re
patn = re.sub(pattern, repl, sentence)
# pattern is the special RE expression for finding the brackets.
# repl is a string which replaces with the selected things by pattern
# RE is searched in sentence string
The regex pattern used for performing our task:
Note: Here, we have used 2 syntactic characters of regex for doing this-
- […] is a character class that is used to match any one of the characters presents between them
- \ is used for matching the special characters for this, we have brackets as a special character
Here is how it works:
Example 1: Program for removing the brackets with regular expressions from the string
Python3
import re
text = "Welcome to geeks for geeks [GFG] A (computer science portal)"
patn = re.sub(r "[\([{})\]]" , "", text)
print (patn)
|
Output:
Welcome to geeks for geeks GFG A computer science portal
Now seems like our script is working well. Let’s try the same in a text file. Python enables us to handle files.
Note: For more information, refer File handling in Python.
Example 2: Program for removing brackets from the text file
File Used:
Python3
import re
with open ( 'data.txt' , 'r' ) as f:
text = f.read()
patn = re.sub(r "[\([{})\]]" , "", text)
print (patn)
|
Output:
Example 2: Appending the changes to a new text file
File Used:
Python3
import re
with open ( 'input.txt' , 'r' ) as f:
text = f.read()
pattern = re.sub(r "[\([{})\]]" , "", text)
with open ( 'output.txt' , 'w' ) as my_file:
my_file.write(pattern)
|
Output:
Last Updated :
21 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...