这是我的代码:
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/