[英]How do i remove specific text from the file?
我試圖從這個字幕文件中刪除一些特定的上下文,但是當我嘗試這樣做時,它會將文件完全擦除為空白。 請幫我。 謝謝你。
x=open("text.txt",'rb')for sub in x:
sub=sub.strip()
if sub.startswith('0',0,28):
x.remove()
//字幕文件
您可以使用正則表達式來替換它。
正則表達式模式: [0-9]+\\n[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]+ --> [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]+\\n
import re
with open("text.txt") as file:
txt = re.sub(r"[0-9]+\n[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]+ --> [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]+\n", "", file.read())
print(txt)
text.txt 的示例內容
1
00:00:26,720 --> 00:00:31,720
Subtitles by <font color="#ff0000">explosiveskull</font>
Sync by <font color="#00ffff">GoldenBeard</font>
2
00:00:43,752 --> 00:00:45,621
(MEN CHATTERING INDISTINCTLY)
輸出
Subtitles by <font color="#ff0000">explosiveskull</font>
Sync by <font color="#00ffff">GoldenBeard</font>
(MEN CHATTERING INDISTINCTLY)
打開文件並將文件內容存儲在一個字符串中:
with open("test.txt") as x:
data = x.read()
現在根據需要刪除/添加任何數據到該字符串:
// operations that you wish to perform on the content
再次以w+模式打開,將修改后的內容寫入其中:
with open("test.txt", w+) as x:
data = x.write(content)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.