2016-07-14 147 views
0

我最近在Python 3.5中編寫了這個腳本來爲一個給定的字符串搜索一個文本文件,我似乎無法弄清楚如何讓腳本在單詞「log」之後移除其餘的單詞,顯示在行中。Python文件搜索腳本

file1 = input ('What is the name of the file? ') 
search_string = input ('What are you looking for? ') 
with open(file1) as cooldude: 
for line in cooldude: 
    line = line.rstrip() 
    if search_string in line: 
     print(line) 

一個例子是: 「我想保持這種東西登錄我不想要這個東西。」 我想刪除包括單詞「日誌」後的所有內容。謝謝!

+0

如果一個行包含單詞「** **登錄IC」或「** **日誌arithm 「?或「ana ** log **」? –

+0

我要搜索的文件不會有任何該行中的單詞。 – krisP

+0

so'line,sep,_ = line.partition('log')'或'line = line.split('log')[0]' –

回答

0

如果你想要的是在一條線上模式'log'之後刪除文本的一部分,你可以使用任何一種str.partition輸出的第一部分或str.split第0指數:

>>> line = "I want to keep this stuff. log I don't want this stuff." 

>>> line1,sep,_ = line.partition('log') 
>>> line1 
"I want to keep this stuff. " 

>>> line2 = line.split('log')[0] 
>>> line2 
"I want to keep this stuff. " 

對於輕微的變化,最後'log'後人們可以只取出部分用str.rsplitmaxsplit=1

>>> line = "I want to keep this stuff. log log I don't want this stuff." 
>>> line3 = line.rsplit('log',1)[0] 
>>> line3 
"I want to keep this stuff. log"