gpt4 book ai didi

python - 使用 Python 删除特定单词后的多行

转载 作者:行者123 更新时间:2023-12-04 03:34:16 24 4
gpt4 key购买 nike

我想使用 Python 删除 .txt 文件中文章的最后一部分(即引用部分)。 “整个部分”是指“引用”一词之后的所有内容:

References Section

有没有办法使用正则表达式或任何其他方法删除“References”一词后的所有内容?

我试过下面的代码,但是,它只删除了“References”一词之后的第一行:

input_file = open("remove.txt", 'r', encoding= 'utf-8')
prev_line = False
lines =[]
for line in input_file:
if not prev_line:
lines.append(line)
prev_line=False
if "References" in line:
prev_line=True
input_file.close()

input_file = open("input.txt", 'w')
for line in lines:
input_file.write(line)
input_file.close()

谢谢

最佳答案

可以使用read读取整个文件。

text = input_file.read()

find 是一种用于定位子字符串的字符串方法。然后我们可以使用字符串切片只选择所需单词之前的所有内容,在本例中为 “References”

ans = text[:text.find("References")]

关于python - 使用 Python 删除特定单词后的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67247815/

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