使用Python编写的简单文字搜索工具
发布时间:2023-12-04 12:47:29
下面是一个使用Python编写的简单文字搜索工具的示例代码:
def text_search(text, keyword):
"""
搜索给定文本中是否包含指定的关键词,并返回匹配的行数和内容。
:param text: 要搜索的文本
:param keyword: 要搜索的关键词
:return: 匹配的行数和内容的列表
"""
lines_with_keyword = []
lines = text.split('
')
for i, line in enumerate(lines):
if keyword in line:
lines_with_keyword.append((i+1, line))
return lines_with_keyword
# 示例用法
example_text = """
Hello, this is a sample text.
It contains multiple lines.
We will search for a keyword in this text.
"""
keyword_to_search = 'sample'
results = text_search(example_text, keyword_to_search)
if results:
print(f'找到了{len(results)}行包含关键词"{keyword_to_search}"的内容:')
for line_number, line_content in results:
print(f'第{line_number}行:{line_content}')
else:
print(f'没有找到包含关键词"{keyword_to_search}"的内容。')
上述代码定义了一个名为text_search的函数,该函数接受要搜索的文本和关键词作为参数,并返回匹配的行数和内容的列表。函数通过将文本拆分为行,并逐行搜索关键词来实现。
在示例用法中,我们将一个包含多行文本的字符串传递给text_search函数,同时指定要搜索的关键词为'sample'。然后,我们打印出找到的匹配行数和内容。
如果运行该示例代码,输出将如下所示:
找到了1行包含关键词"sample"的内容: 第2行:Hello, this is a sample text.
上述示例仅仅是一个简单的文字搜索工具的基本实现。根据需要,你可以进一步扩展该工具,以支持更复杂的搜索功能,例如大小写不敏感、正则表达式匹配等。
