python - 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.
暂时没找到答案,求大神帮忙
解决方案
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
这会在查找句点之前跳过整个长度。
推荐阅读
- c++ - 使用boost从pid获取“二进制文件”/“可执行文件”的路径?
- json - 使用 json 内容的 kotlin jvm 字符串模板
- intellij-idea - 是否可以在 LESS 中设置文件观察器以使输出文件的名称与源文件不同?
- python - 在熊猫的两列中查找关系值
- botframework - 英雄卡中没有换行的文字
- windows - cmd.exe 的环境变量存储在哪里?
- javascript - 在 ipywidgets 中创建子小部件会使用 ViewList 和 create_child_view 产生错误
- spring - 问题:ManyToMany 实体的规范查询语法
- javascript - 如何防止使用 jQuery 验证在我的输入字段中写入 url?
- android - Firebase ChildEventListener 在 Java Admin SDK 中长时间不起作用