|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
如何显示找到的关键字的前后10个字的内容
源代码如下,该如何修改
import os
def search_keywords_in_html(directory, keyword):
files = os.listdir(directory)
for file in files:
if file.endswith('.html'):
file_path = os.path.join(directory, file)
with open(file_path, 'r', encoding='UTF-8') as f:
content = f.read()
if keyword in content:
print(f"found '{keyword}' in {file}")
# 指定要搜索的目录和关键字
directory = 'f:\\'
keyword = input('请输入要查询的内容')
search_keywords_in_html(directory, keyword)
本帖最后由 Mike_python小 于 2023-7-19 20:14 编辑
你可以在找到关键字时,使用字符串切片操作来获取前后10个字符的内容。下面是修改后的代码示例:
- import os
- def search_keywords_in_html(directory, keyword):
- files = os.listdir(directory)
- for file in files:
- if file.endswith('.html'):
- file_path = os.path.join(directory, file)
- with open(file_path, 'r', encoding='UTF-8') as f:
- content = f.read()
- if keyword in content:
- keyword_index = content.index(keyword)
- start_index = max(0, keyword_index - 10)
- end_index = min(len(content), keyword_index + len(keyword) + 10)
- context = content[start_index:end_index]
- print(f"Found '{keyword}' in {file}. Context: {context}")
- # 指定要搜索的目录和关键字
- directory = 'f:\\'
- keyword = input('请输入要查询的内容:')
- search_keywords_in_html(directory, keyword)
复制代码
这段代码会打印出包含关键字的文件名以及关键字所在位置的前后10个字符的内容。
希望对你有所帮助!如果你还有其他问题,请随时提问。
球一个最佳答案谢谢啦!这对我非常重要!  
|
|