我有一些字幕文件,我不打算学习这些字幕中的每一个单词,没有必要学习一些硬性词汇,比如:锁骨颅骨发育不良。
我在这里找到了这个脚本:Remove words from a cell that aren't in a list。但我不知道如何修改或运行它。(我正在使用linux)
下面是我们的例子:
字幕文件(.srt):
2
00:00:13,000 -> 00:00:15,000
锁骨颅发育不良的人很好。
300个常用单词的单词列表(.txt):
...
人民
使用
是
好的
..。
我们需要的输出(.srt)
2
00:00:13,000 -> 00:00:15,000
有**的人很好。
或者在可能的情况下标记它们(.srt):
2
00:00:13,000 -> 00:00:15,000
锁骨颅发育不良的人很好。
如果有一个解决方案只适用于纯文本(没有时间代码),没关系,只需解释如何运行它
谢谢。
发布于 2021-01-03 14:42:48
下面只处理每个'.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]]然后,产出如下:
2
00:00:13,000 --> 00:00:15,000
People with cleidocranial* dysplasia* are good.解释:
第一个'.srt'.
set (用于快速成员资格测试)。
glob查找每个文件中的所有文件名,我们构造一个新的文件名作为'..._new.srt'.
line.strip()开始,enumerate删除了后面的换行符。
line.strip().split()将行拆分成单词,但它会将'good.'保留为最后一个单词;不太好。使用的正则表达式通常用于分隔单词(特别是,它保留在单引号中,例如"don't";它可能是您想要的,也可能不是您想要的,当然可以随意调整)。
r"([\w']+)",而不是在非单词字符上拆分,这样我们就可以在parts中同时使用单词和分隔它们的内容。例如,['', 'People', ', ', 'who', ' ', 'are', ' ', 'good', '.'].
'People, who are good.'本身就是parts的所有其他元素,从索引1开始。
'*'替换单词,如果它们的小写形式不在keep_words.
发布于 2021-01-03 14:54:05
您可以简单地运行这样一个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*替换所有不在普通word文件中的单词,保留原始文件,并将所有内容放入新的输出文件
https://stackoverflow.com/questions/65550885
复制相似问题