Python,从关键字打印到下一个点



所以这是我的代码

a = input("Enter file name: ")
b = input("Enter keyword: ")
def search_string_in_file(file_name, string_to_search):
line_number = 0
results = ""
with open(file_name, 'r' , encoding='latin1') as read_obj:
for line in read_obj:
line_number += 1
if string_to_search in line:
print(line)
search_string_in_file(a, b)

此时,它会打开您在第一次输入中设置的文件,并逐行搜索该文件以查找您在第二次输入中设定的关键字。

就像现在一样,它打印出关键字所在的整行。

我想做的只是从关键字开始打印到下一个点。

例如:file.txt

This is my house. I like it.
But my girlfriend hates it, but that's ok.

keyword=我的

实际结果打印两行,因为这两行都包含";我的";。但它只应该打印这个:

my house.
my girlfriend hates it, but that's ok.

到目前为止还没有找到任何答案,请帮助我

我们可以使用运算符[]拼接到字符串line中。在str.find()的帮助下,我们可以确定需要打印的小部分。来自文件:

The find() method returns the index of first occurrence of the
substring (if found). If not found, it returns -1.

以下是我们如何重写代码:

a = input("Enter file name: ")
b = input("Enter keyword: ")
def search_string_in_file(file_name, string_to_search):
line_number = 0
results = ""
with open(file_name, 'r' , encoding='latin1') as read_obj:
for line in read_obj:
line_number += 1
word_index = line.find(string_to_search)  # position of first letter of the word
if (word_index != -1):  # meaning the word was found
period_index = line.find('.', word_index)  # position of first period after start of word
print(line[word_index:period_index]
search_string_in_file(a, b)

请记住,如果有一段时间,这将变得不稳定内部string_to_search。在这种情况下,为了确保打印出整个字符串,请执行以下操作:

period_index = line.find('.', word_index+len(string_to_search))

这在查找周期之前跳过string_to_search的整个长度。

最新更新