Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除[]、{}和()_Python_Python 3.x_Regex - Fatal编程技术网

Python 删除[]、{}和()

Python 删除[]、{}和(),python,python-3.x,regex,Python,Python 3.x,Regex,file1.txt包含: Thailand,[a] officially the Kingdom of Thailand and formerly known as Siam,[b] is a country in Southeast Asia. 我想删除[]和()之间的单词。预期产出为: Thailand, officially the Kingdom of Thailand and formerly known as Siam, is a country in Southeast Asia

file1.txt
包含:

Thailand,[a] officially the Kingdom of Thailand and formerly known as Siam,[b] is a country in Southeast Asia.
我想删除
[]
()
之间的单词。预期产出为:

Thailand, officially the Kingdom of Thailand and formerly known as Siam, is a country in Southeast Asia.
这是我的代码:

with open('file1.txt') as file1:
    file1 = file1.read()
test = re.sub(r'[\(\[].*[\)\]]', '', file1)
我的代码删除
[a]
[b]
之间的所有单词。示例输出:

Thailand is a country in Southeast Asia.

当您使用
[.*]
时,它会进行贪婪匹配,因此从
[a
b]
的所有内容都会被匹配并替换为空字符串
'

使用
[.?]
时,它与
[]
中的任何字符
零次或1次
匹配。所以
[a]
[b]
是匹配的

重新导入
将open('file1.txt')作为file1:
file1=file1.read()
test=re.sub(r'[\(\[.?[\)\]]','',文件1)
打印(测试)

你的
*
是一个贪婪的匹配,把它改成
*?
它应该可以工作。那里有什么词?例如,输入是否可以包含
[foo(bar)]
((x))
?在
(…)
[…]中是否可以有换行符?您需要Python解决方案,还是普通的Unix文本处理工具也可以?如何处理不平衡括号?主题提到
[]
()
{}
,但正文和您的尝试仅包括
[]
()
。哪一个?非常感谢你,我的救命恩人。我把它改成*?您可能想添加一些解释,为什么这种方法解决了OPs最初尝试的缺点(您的帖子出现在我的“低质量帖子”评论队列中…),使用
[^\]*
比dot上的懒惰量词更有效。非常感谢。你们是我的救命恩人!