2016-07-14 150 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"