[英]Remove words from a subtitle file that aren't in a wordlist (of common words)
我有一些字幕文件,我不打算學習這些字幕中的每一個單詞,沒有必要學習一些硬術語,比如:鎖骨、發育不良......
我在這里找到了這個腳本: Remove words from a cell that are not in a list 。 但我不知道如何修改或運行它。 (我正在使用Linux)
這是我們的示例:
字幕文件(.srt):
2
00:00:13,000 --> 00:00:15,000
有鎖顱發育不良的人是好的。
3000 個常用詞的詞表 (.txt):
...
人們
和
是
好的
...
Output 我們需要(.srt) :
2
00:00:13,000 --> 00:00:15,000
有 * * 的人很好。
或者在可能的情況下標記它們(.srt):
2
00:00:13,000 --> 00:00:15,000
患有鎖顱*發育不良*的人很好。
如果有一個只使用純文本(沒有時間碼)的解決方案,沒關系,只需解釋如何運行它
謝謝你。
以下僅處理每個'.srt'
文件的第 3 行。 它可以很容易地適應處理其他行和/或其他文件。
import os
import re
from glob import glob
with open('words.txt') as f:
keep_words = {line.strip().lower() for line in f}
for filename_in in glob('*.srt'):
filename_out = f'{os.path.splitext(filename_in)[0]}_new.srt'
with open(filename_in) as fin, open(filename_out, 'w') as fout:
for i, line in enumerate(fin):
if i == 2:
parts = re.split(r"([\w']+)", line.strip())
parts[1::2] = [w if w.lower() in keep_words else '*' for w in parts[1::2]]
line = ''.join(parts) + '\n'
fout.write(line)
結果(對於您提供的subtitle.rst
作為示例:
! cat subtitle_new.rst
2
00:00:13,000 --> 00:00:15,000
People with * * are good.
替代方案:只需在詞匯表外的單詞旁邊添加一個'*'
:
# replace:
# parts[1::2] = [w if w.lower() in keep_words else '*' for w in parts[1::2]]
parts[1::2] = [w if w.lower() in keep_words else f'{w}*' for w in parts[1::2]]
output 是:
2
00:00:13,000 --> 00:00:15,000
People with cleidocranial* dysplasia* are good.
解釋:
open
用於讀取所有想要的單詞,確保它們是小寫的,然后將它們放入一個set
(用於快速成員資格測試)。glob
來查找所有以'.srt'
結尾的文件名。'..._new.srt'
。i == 2
行(即第 3 行,因為默認情況下enumerate
從 0 開始)。line.strip()
刪除尾隨的換行符。line.strip().split()
將行拆分為單詞,但它會留下'good.'
最后一句話; 不好。 使用的正則表達式通常用於拆分單詞(特別是,它留下單引號,例如"don't"
;它可能是也可能不是您想要的,當然可以隨意調整)。r"([\w']+)"
而不是在非單詞字符上進行拆分,以便我們同時擁有單詞以及將它們分開的parts
。 例如, 'People, who are good.'
變為['', 'People', ', ', 'who', ' ', 'are', ' ', 'good', '.']
。parts
的所有其他元素,從索引 1 開始。keep_words
中,我們將其替換為'*'
。您可以像這樣簡單地運行 python 腳本:
with open("words.txt", "rt") as words:
#create a list with every word
wordList = words.read().split("\n")
with open("subtitle.srt", "rt") as subtitles:
with open("subtitle_output.srt", "wt") as out:
for line in subtitles.readlines():
if line[0].isdigit():
#ignore the line as it starts with a digit
out.write(line)
continue
else:
for word in line.split():
if not word in wordList:
out.write(line.replace(word, f"*{word}*"))
此腳本將用修改后的*word*
替換不在常用單詞文件中的每個單詞,保留原始文件並將所有內容放入新的 output 文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.