gpt4 book ai didi

python - 如何将特定句子与下一个句子一起删除?

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:25 24 4
gpt4 key购买 nike

我正在处理文本文件中的文字记录,我需要删除一些特定的行。

这是一个例子:

Child:    Mom   can   I    have  an  ice cream?
grammar: noun verb pro verb art noun
Mom: Here is some money, go buy that ice cream
grammar: adv verb pro noun verb verb pro noun
Child: But I want more money, I want the big ice cream
grammar: conj pro verb adj noun pro verb art adj noun

如果我想删除所有妈妈的句子和后面的语法句子,而我想保留 child 的语法句子,我可以使用什么Python脚本?

最佳答案

它惰性地成对地从文件中读取,并在特定条件下跳过生成值。下面的代码函数将过滤的行转储到另一个文件。

def yield_filtered_lines(filename):
with open(filename) as f:
while True:
sentence = f.readline()
grammar = f.readline()
if not sentence or not grammar:
break # EOF
if sentence.startswith("Mom:"):
continue
yield sentence
yield grammar

with open('filtered.txt', 'w') as f:
for l in yield_filtered_lines("sentences.txt"):
f.write(l)

sentences.txt内容:

Child:    Mom   can   I    have  an  ice cream?
grammar: noun verb pro verb art noun
Mom: Here is some money, go buy that ice cream
grammar: adv verb pro noun verb verb pro noun
Child: But I want more money, I want the big ice cream
grammar: conj pro verb adj noun pro verb art adj noun

filtered.txt内容:

Child:    Mom   can   I    have  an  ice cream?
grammar: noun verb pro verb art noun
Child: But I want more money, I want the big ice cream
grammar: conj pro verb adj noun pro verb art adj noun

关于python - 如何将特定句子与下一个句子一起删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30149838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com