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上的懒惰量词更有效。非常感谢。你们是我的救命恩人!