繁体   English   中英

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

[英]Python: How to remove part of a string starting at a keyword for multiple lines?

这是我的代码:

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

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

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

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

使用正则表达式查找“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()返回一个元组,其中包含您想要查找的内容的起始 position 和结尾 position(“test”)

re.search("test",line).span()[1]为您提供行中单词“test”的结尾 position

最后line[:index ]给你一段line ,直到它找到“测试”的结尾 position

如果您知道“测试”出现在每一行中,那么您真的不需要正则表达式。 只需在test开始的索引处分割字符串加上test的长度

with open('locations.txt', 'r') as f, open('output.txt', 'w') as fo:
for line in f:
    fo.write(line[:line.index('test') + len('test')])

看看split() .split(separator, maxsplit)将在关键字和 append 处将字符串切片到一个列表中,然后返回该列表。 如果关键字多次出现,则将 maxsplit 设置为 1,但您只需要第一个。

with open('locations.txt', 'r') as f, open('output.txt', 'w') as fo:
    for line in f:
        new_string = line.split('test')[0] + "test"#  split removes the separator keyword
        fo.write(new_string)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM