我最近在Python 3.5中编写了这个脚本来搜索给定字符串的文本文件,我似乎无法弄清楚如何让脚本在“log”一词出现之后删除其余的单词。线。
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)
一个例子是: “我想保留这些东西。日志我不想要这些东西。” 我想要删除所有内容,包括单词“log”。谢谢!
答案 0 :(得分:0)
如果你想要的只是在一行中的模式'log'
之后删除文本的一部分,你可以使用str.partition
输出的第一部分或第0个索引str.split
:
>>> 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'
maxsplit=1
使用str.rsplit
删除最后>>> 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"
后的部分:
RNGScope