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

标签 python replace

我想使用 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/

相关文章:

python - 使用 tf.io.decode_jpeg 导入后出现 TypeError : Image data cannot be converted to float with plt. imshow

python - df [‘’ ] 和 df[ [‘’ ]] 有什么区别

Python:使用虚拟类传递变量名?

python - 仅在某些位置替换表示日期的字符串

c# - 如何一次性执行多个字符串替换?

远程 MS Windows 主机上的 Python 子进程

python:如何找到不是子字符串而是子图片?

javascript - Node.js 获取字符串中所有出现的子字符串

javascript - 如何使用 jQuery 将所有相对路径设置为绝对路径?

Javascript .replace()/正则表达式,代码为字符串