Python文件搜索脚本

2024-04-26 02:18:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近在python3.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)

例如: “我想保留这些东西。“我不想要这些东西。” 我想删除之后的一切,包括“日志”一词。谢谢!你知道吗


Tags: the字符串in脚本logforinputsearch
1条回答
网友
1楼 · 发布于 2024-04-26 02:18:51

如果您只想删除行中模式'log'之后的文本部分,则可以使用^{}输出的第一部分或^{}的第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. "

对于一个微小的变化,可以使用^{}maxsplit=1来移除最后一个'log'之后的部分:

>>> 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"

相关问题 更多 >