import zipfile
import re
def count_and_extract_context(zip_path, target_word, context_len=100, output_file="context_results.txt"):
total_count = 0
# 打开输出文件,准备写入上下文
with open(output_file, 'w', encoding='utf-8') as out_f:
out_f.write(f"=== 关键词 '{target_word}' 的上下文提取结果 ===\n\n")
# 打开压缩包
with zipfile.ZipFile(zip_path, 'r') as zf:
# 遍历所有txt文件
for file_info in zf.infolist():
if file_info.filename.endswith('.txt'):
try:
with zf.open(file_info, 'r') as f:
content = f.read().decode('utf-8')
# 正则匹配完整单词(保留大小写信息,但匹配时不区分大小写)
pattern = re.compile(rf'\b{target_word}\b', re.IGNORECASE)
matches = pattern.finditer(content) # 使用finditer获取匹配位置
file_count = 0
for match in matches:
file_count += 1
total_count += 1
# 获取关键词在文本中的位置
start = match.start()
end = match.end()
# 计算上下文截取范围(避免越界)
context_start = max(0, start - context_len)
context_end = min(len(content), end + context_len)
# 提取上下文(用[...]标记关键词)
context = (
content[context_start:start] +
f"[***{content[start:end]}***]" + # 关键词加粗标记
content[end:context_end]
)
# 写入上下文到文件
out_f.write(f"文件: {file_info.filename}\n")
out_f.write(f"位置: 第{start}个字符附近\n")
out_f.write(f"上下文: {context}\n")
out_f.write("-" * 100 + "\n") # 分隔线
# 可选:打印每个文件的统计结果
# if file_count > 0:
# print(f"{file_info.filename}: {file_count}次")
except UnicodeDecodeError:
print(f"警告:文件 {file_info.filename} 编码不是utf-8,已跳过")
out_f.write(f"警告:文件 {file_info.filename} 编码不是utf-8,已跳过\n\n")
return total_count
# 使用示例
zip_file_path = "python-3.14-docs-text.zip" # 压缩包路径
target = "名称" # 要统计的关键词(可替换为"name")
context_length = 100 # 上下文长度(每个方向的字符数)
output_path = "contexts_"+target+".txt" # 输出文件路径
total = count_and_extract_context(zip_file_path, target, context_length, output_path)
print(f"压缩包中所有txt文件里'{target}'一词共出现 {total} 次")
print(f"上下文已保存到 {output_path}")