Python:如何删除以多行关键字开头的字符串的一部分?

标签 python string file text replace

这是我的代码:

with open('locations.txt', 'r') as f, open('output.txt', 'w') as fo:
for line in f:
    fo.write(line.replace('test'[:-1], ''))

我有一个包含多行文本的文件:

This is a test the cat jumped around
This is another test the dog jumped under
This is a third test the cow jumped over

我希望能够打开文本文件,并删除每行中单词“test”之后的所有内容。所以结果看起来像:

This is a test
This is another test
This is a third test

我正在尝试使用 .replace() 但使用参数 -1 它只是删除了测试中的最后一个字母以外的所有内容。我真的不确定如何将“test”这个词作为输入,然后让它在每一行之后删除字符串的其余部分。

最佳答案

使用正则表达式查找“​​test”在您的字符串中首次出现的位置

with open('locations.txt', 'r') as f, open('output.txt', 'w') as fo:
    for line in f:
        index = re.search("test",line).span()[1]
        fo.write(line[:index ])

这里是分割:

re.search("test",line)line 中搜索 "test"

re.search("test",line).span() 返回一个元组,其中包含您要查找的内容("test")的起始位置和结束位置

re.search("test",line).span()[1] 给出单词“test”在行中的结束位置

最后 line[:index ] 给你一段 line 直到它找到“test”的结束位置

关于Python:如何删除以多行关键字开头的字符串的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73507171/

相关文章:

ios - 在本地存储和删除文本文件 ios objective c

Python cgi 脚本仅在完成后才在浏览器中显示输出

java - 在我的应用程序中共享静态字符串的策略

python - 如何创建虚拟文件作为内存缓冲区

c# - c#计算两个文本文件的百分比差异

python - 如何在matplotlib中显示LaTeX f字符串

java - 如何使用Java在多线程中复制文件

python - Pandas 'partial melt' 或 'group melt'

python - 将 pandas 数据框中的空格替换为 NAN

Python 使用 BS4 在整个 XML 中添加子子元素