如何从Python的文本文件中删除括号?
有时很难从文本文件中删除我们不需要的括号。因此, Python可以为我们做到这一点。在Python,我们可以借助正则表达式去除括号。
句法:
# import re module for using regular expression
import re
patn = re.sub(pattern, repl, sentence)
# pattern is the special RE expression for findind the brackets.
# repl is a string which replaces with the selected things by pattern
# RE is searched in sentence string
用于执行我们的任务的正则表达式模式:
注意:在这里,我们使用了正则表达式的 2 个语法字符来执行此操作 -
- […] 是一个字符类,用于匹配它们之间出现的任何一个字符
- \ 用于为此匹配特殊字符,我们将括号作为特殊字符
下面是它的工作原理:
示例 1:从字符串去除带有正则表达式的括号的程序
Python3
# importing re module for creating
# regex expression
import re
# string for passing
text = "Welcome to geeks for geeks [GFG] A (computer science portal)"
# creating the regex pattern & use re.sub()
# [\([{})\]] is a RE pattern for selecting
# '{', '}', '[', ']', '(', ')' brakcets.
patn = re.sub(r"[\([{})\]]", "", text)
print(patn)
Python3
# importing re module for creating
# regex expression
import re
# reading line by line
with open('data.txt', 'r') as f:
# looping the para and iterating
# each line
text = f.read()
# getting the pattern for [],(),{}
# brackets and replace them to empty
# string
# creating the regex pattern & use re.sub()
patn = re.sub(r"[\([{})\]]", "", text)
print(patn)
Python3
# importing re module for creating
# regex expression
import re
# reading line by line
with open('input.txt', 'r') as f:
# store in text variable
text = f.read()
# getting the pattern for [],(),{}
# brackets and replace them to empty string
# creating the regex pattern & use re.sub()
pattern = re.sub(r"[\([{})\]]", "", text)
# Appending the changes in new file
# It will create new file in the directory
# and write the changes in the file.
with open('output.txt', 'w') as my_file:
my_file.write(pattern)
输出:
Welcome to geeks for geeks GFG A computer science portal
现在看起来我们的脚本运行良好。让我们在文本文件中尝试相同的操作。 Python使我们能够处理文件。
注意:有关更多信息,请参阅Python的文件处理。
示例 2:从文本文件中删除括号的程序
使用的文件:
蟒蛇3
# importing re module for creating
# regex expression
import re
# reading line by line
with open('data.txt', 'r') as f:
# looping the para and iterating
# each line
text = f.read()
# getting the pattern for [],(),{}
# brackets and replace them to empty
# string
# creating the regex pattern & use re.sub()
patn = re.sub(r"[\([{})\]]", "", text)
print(patn)
输出:
例2:追加更改到一个新的文本文件
使用的文件:
蟒蛇3
# importing re module for creating
# regex expression
import re
# reading line by line
with open('input.txt', 'r') as f:
# store in text variable
text = f.read()
# getting the pattern for [],(),{}
# brackets and replace them to empty string
# creating the regex pattern & use re.sub()
pattern = re.sub(r"[\([{})\]]", "", text)
# Appending the changes in new file
# It will create new file in the directory
# and write the changes in the file.
with open('output.txt', 'w') as my_file:
my_file.write(pattern)
输出: