简体   繁体   English

如何删除字符串中 2 个不同字符之间的字符

[英]how do i remove characters between 2 different characters inside a string

So i have this inside a text file:所以我在一个文本文件中有这个:

"00:00:25,58 --> 00:00:27,91 (DRAMATIC MUSIC PLAYING)"

I want to remove characters inside and including the braces itself so:我想删除里面的字符并包括大括号本身:

"00:00:25,58 --> 00:00:27,91 "


eng_sub = open(text).read()
eng_sub2 = re.sub("\(", "", eng_sub)
new_eng_sub = re.sub("\)", "", eng_sub2)

open(text, "w").write(new_eng_sub)

I've tried using sub() and it removes a character but what i really want to do is manipulate characters between those 2 (ie "(", ")") characters.我试过使用 sub() 并删除了一个字符,但我真正想做的是在这 2 个字符(即“(”、“)”)之间操作字符。

I don't know how to do it.我不知道该怎么做。 thank you for your help.感谢您的帮助。

You may try matching on the pattern \(.*?\) :您可以尝试匹配模式\(.*?\)

eng_sub = open(text).read()
eng_sub2 = re.sub(r'\(.*?\)', '', eng_sub)

open(text, "w").write(eng_sub2)

Indeed, you can't use the "sub" method which will simply delete the pattern.实际上,您不能使用只会删除模式的“sub”方法。 But what you can do (and which is not too complex) is to use "findall" (also present in the re library) which allows you to extract a pattern in the STR Here's a simple example:但是你可以做的(并且不太复杂)是使用“findall”(也存在于 re 库中),它允许你在 STR 中提取模式这是一个简单的例子:

import re
text = "00:00:25,58 --> 00:00:27,91 (DRAMATIC MUSIC PLAYING)"
print(re.findall(r"\(.*\)", text)[0])

Output: (DRAMATIC MUSIC PLAYING) Output:(戏剧性的(DRAMATIC MUSIC PLAYING)

Once you have extracted what you want to manipulate, you can delete this pattern via sub一旦你提取了你想要操作的东西,你可以通过 sub 删除这个模式

print(re.sub(r"\(.*\)", '', text))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM