|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
不加红色部分正常,加了就只搜索一次
import os
from bs4 import BeautifulSoup
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()
soup = BeautifulSoup(content, "html.parser")
for script in soup(["script", "style"]):
script.extract()
text = soup.text
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = '\n'.join(chunk for chunk in chunks if chunk)
keyword_index = text.find(keyword)
while keyword_index != -1:
start_index = max(0, keyword_index - 30)
end_index = min(len(text), keyword_index + len(keyword) + 30)
text = text[start_index:end_index]
print(f"Found '{keyword}' in '{file}'")
print(text)
keyword_index = text.find(keyword, keyword_index + 1)
# 指定要搜索的目录和关键字
directory = r'e:\html资料'
keyword = input('请输入要查询的内容')
search_keywords_in_html(directory, keyword)
本帖最后由 isdkz 于 2023-7-20 20:03 编辑
这个问题发生在 while keyword_index != -1: 循环中,而具体的原因是你在每次找到一个关键字后,都会把 text 从 start_index 到 end_index 的内容裁剪并赋值给 text 。这意味着在每次循环迭代后, text 都会变得更短,进而可能导致关键字无法在后续的搜索中被发现。
这就是为什么只搜到一次关键字的原因。
解决这个问题的方法是创建一个新的字符串来存储裁剪的内容,而不是直接修改 text 。
代码修改如下:
- # 省略无关代码
- while keyword_index != -1:
- start_index = max(0, keyword_index - 30)
- end_index = min(len(text), keyword_index + len(keyword) + 30)
- clipped_text = text[start_index:end_index] # 使用新的变量存储裁剪的内容
- print(f"Found '{keyword}' in '{file}'")
- print(clipped_text)
- keyword_index = text.find(keyword, keyword_index + 1) # 这里仍然使用原始的 text 进行查找
- # 省略无关代码
复制代码
在这个修改后的代码中, clipped_text 用于存储和打印裁剪的文本,而原始的 text 则被用于进行关键字的查找。
|
|