我想使用 Python 删除 .txt 文件中文章的最后一部分(即引用部分)。 “整个部分”是指“引用”一词之后的所有内容:
有没有办法使用正则表达式或任何其他方法删除“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/