這是我的代碼:
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 的引數它只是洗掉了除測驗中的最后一個字母之外的所有內容。我真的不確定如何將“test”這個詞作為輸入,然后讓它在每一行之后洗掉字串的其余部分。
uj5u.com熱心網友回復:
使用正則運算式查找“??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)搜索"test"在line
re.search("test",line).span()回傳一個元組,其中包含您要查找的內容的起始位置和結束位置(“測驗”)
re.search("test",line).span()[1]給你行中單詞“test”的結束位置
終于line[:index ]給你一個片段,line直到它找到“測驗”的結束位置
uj5u.com熱心網友回復:
如果您知道“測驗”出現在每一行中,那么您真的不需要正則運算式。只需在 were 的索引處分割字串,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')])
uj5u.com熱心網友回復:
看看split()。.split(separator, maxsplit)將在關鍵字處對字串進行切片并將它們附加到一個串列中,然后回傳該串列。如果關鍵字多次出現,則將 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505066.html
