[英]How do I extract specific lines from a string starting from a keyword and ending at a different keyword in 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.