首页 > 解决方案 > 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)

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

现在它打印找到关键字的整行。

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

例如:文件.txt

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

关键字 = 我的

实际结果会打印两行,因为这两行都包含“my”。但它只应该打印这个:

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

暂时没找到答案,求大神帮忙

标签: pythonstring

解决方案


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这会在查找句点之前跳过整个长度。


推荐阅读