len(repr("\n\n\n"))为什么长度为8

本文探讨了Python中repr函数的工作原理,特别是在处理特殊字符时的行为。通过实例解释了为什么repr(' ')的长度为8,揭示了repr与str函数在对象转换上的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作为python的初学者,我对这个len翻译repr(object)对象的长度比较感兴趣,然后试了一下这个方法,
在这里插入图片描述
当时我就纳闷了,这怎么是8呢,\n\n\n不应该是9?

不知道有没有试过的小伙伴可以给我解释一下嘛,我很疑惑.

enmmm 转手就解决了这个问题
原来repr以字符串形式转换了整个对象,并没有像str那样对对象进行一些转义,repr只是将对象用字符串包围

所以repr("\n\n\n") 等价于 ’ “\n\n\n” ’ ------> 加上一对双引号就是8个.

还是用这版脚本,加上忽略大小写匹配机制就行 import os import re import sys def extract_keywords(keyword_file, output_file): """增强版关键字搜索,解决匹配失败问题""" # 1. 增强的关键字读取(支持注释和空行) try: with open(keyword_file, 'r', encoding='utf-8', errors='replace') as kf: raw_content = kf.read() # 支持#号注释和空行 keywords = [kw.strip() for line in raw_content.splitlines() for kw in re.split(r'[,;|]+', line.split('#')[0].strip()) if kw.strip()] except Exception as e: print(f"❌ 读取关键字文件失败: {str(e)}") return False if not keywords: print("⚠️ 警告:未找到有效关键字") return False print(f"已加载 {len(keywords)} 个关键字: {', '.join(keywords[:5])}{'...' if len(keywords) > 5 else ''}") # 2. 调试模式:显示实际加载的关键字 debug_mode = input("启用调试模式? (y/n) [默认n]: ").lower() == 'y' if debug_mode: print("\n[调试] 实际加载关键字列表:") for i, kw in enumerate(keywords, 1): print(f"{i}. {repr(kw)} (长度:{len(kw)})") # 3. 获取当前目录 current_dir = os.getcwd() print(f"搜索目录: {current_dir}") # 4. 增强的匹配逻辑 total_matches = 0 processed_files = 0 match_details = [] # 存储详细匹配信息 with open(output_file, 'w', encoding='utf-8') as of: of.write(f"搜索目录: {current_dir}\n关键字列表: {', '.join(keywords)}\n") of.write("=" * 80 + "\n") for filename in os.listdir(current_dir): filepath = os.path.join(current_dir, filename) # 跳过目录和非文本文件 if (os.path.isdir(filepath) or filename == os.path.basename(output_file) or not is_text_file(filepath)): continue try: with open(filepath, 'r', encoding='utf-8', errors='replace') as f: file_matches = 0 file_content = f.read() # 5. 增强的匹配检测 for kw in keywords: # 处理特殊字符转义 safe_kw = re.escape(kw) pattern = re.compile(safe_kw) matches = pattern.finditer(file_content) for match in matches: start_pos = match.start() # 获取上下文(匹配行及前后行) line_start = file_content.rfind('\n', 0, start_pos) + 1 line_end = file_content.find('\n', start_pos) if line_end == -1: line_end = len(file_content) full_line = file_content[line_start:line_end] # 计算行号(通过计数换行符) line_num = file_content.count('\n', 0, line_start) + 1 # 存储匹配详情 match_details.append({ 'file': filename, 'line': line_num, 'keyword': kw, 'content': full_line.strip() }) file_matches += 1 # 6. 输出结果 if file_matches > 0: of.write(f"\n▼ 文件: {filename}\n") of.write("-" * 80 + "\n") for detail in [m for m in match_details if m['file'] == filename]: of.write(f"行{detail['line']} [匹配 '{detail['keyword']}']: {detail['content']}\n") of.write(f"\n※ 本文件匹配: {file_matches} 处\n") processed_files += 1 total_matches += file_matches # 7. 未匹配时的调试输出 elif debug_mode and file_matches == 0: print(f"\n[调试] 文件 {filename} 扫描完成但未匹配") print(f"文件大小: {os.path.getsize(filepath)} 字节") print("文件前100字符:") print(repr(file_content[:100])) print("关键字测试:") for kw in keywords[:5]: print(f"- '{kw}' 存在? {'是' if kw in file_content else '否'}") except Exception as e: print(f"处理文件 {filename} 时出错: {str(e)}") # 8. 最终统计 print(f"\n处理完成!扫描 {len(os.listdir(current_dir))} 个文件") print(f"匹配文件: {processed_files} 个, 总匹配: {total_matches} 处") if total_matches == 0 and not debug_mode: print("\n⚠️ 警告:未找到任何匹配!建议:") print("1. 运行脚本时启用调试模式") print("2. 检查关键字是否包含空格或特殊字符") print("3. 确认目标文件是否包含关键字") print("4. 尝试在关键字文件中添加转义字符(如\\*)") return True def is_text_file(filepath): """改进的文本文件检测""" try: # 扩展跳过文件类型 binary_exts = ['.exe', '.dll', '.png', '.jpg', '.zip', '.pdf'] if any(filepath.lower().endswith(ext) for ext in binary_exts): return False # 内容检测 with open(filepath, 'rb') as f: return b'\x00' not in f.read(1024) except: return False # 增强的主函数 if __name__ == "__main__": print("=" * 60) print("关键字搜索工具 - 增强匹配版") print("=" * 60) # 交互式配置 # KEYWORD_FILE = input("关键字文件路径 [默认: keywords.txt]: ") or "keywords.txt" # OUTPUT_FILE = input("输出文件路径 [默认: results.txt]: ") or "results.txt" KEYWORD_FILE = "D:\脚本开发keywords.txt" # 关键字文件 OUTPUT_FILE = "search_results.txt" # 输出结果文件 # 执行搜索 extract_keywords(KEYWORD_FILE, OUTPUT_FILE) # 结果提示 if sys.platform.startswith('win'): input("\n按 Enter 键退出...")
最新发布
07-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值