处理MYFILE.txt实体列表:合并literal实体及代码报错解决
问题分析与解决方案
错误原因
你代码里的核心问题是:读取文件后得到的texty是字符串类型,直接遍历texty[::-1]其实是逐个遍历字符串的字符,每个group是单个字符,自然无法用group["entity_group"]访问字典键,这就是"string indices must be integers"错误的由来。
核心需求实现代码
先把文件中的字符串格式数据转换成Python可操作的列表对象,再按文本顺序拼接内容,同时标记metaphoric实体:
import ast # 读取文件并将字符串格式的列表转为Python列表 with open('MYFILE.txt', 'r') as f: entities = ast.literal_eval(f.read()) # 按实体在文本中的起始位置排序,保证顺序正确 entities_sorted = sorted(entities, key=lambda x: x['start']) # 构建最终文本,用**加粗**标记metaphoric实体 final_text_parts = [] for ent in entities_sorted: if ent['entity_group'] == 'literal': final_text_parts.append(ent['word']) else: final_text_parts.append(f"**{ent['word']}**") final_text = ''.join(final_text_parts) print(final_text)
可视化方案
终端彩色标记
用ANSI颜色代码让metaphoric实体在终端显示为红色:
import ast # 终端颜色控制码 RED = '\033[91m' RESET_COLOR = '\033[0m' with open('MYFILE.txt', 'r') as f: entities = ast.literal_eval(f.read()) entities_sorted = sorted(entities, key=lambda x: x['start']) final_text_parts = [] for ent in entities_sorted: if ent['entity_group'] == 'literal': final_text_parts.append(ent['word']) else: final_text_parts.append(f"{RED}{ent['word']}{RESET_COLOR}") print(''.join(final_text_parts))
HTML着色
生成带颜色标记的HTML文件,可在浏览器打开查看:
import ast with open('MYFILE.txt', 'r') as f: entities = ast.literal_eval(f.read()) entities_sorted = sorted(entities, key=lambda x: x['start']) html_parts = [] for ent in entities_sorted: if ent['entity_group'] == 'literal': html_parts.append(ent['word']) else: html_parts.append(f"<span style='color: #ff4444; font-weight: bold;'>{ent['word']}</span>") # 保存为HTML文件 with open('entity_visualization.html', 'w') as f: f.write(f"<html><body style='font-size: 16px;'>{''.join(html_parts)}</body></html>")
内容的提问来源于stack exchange,提问作者Idkwhatywantmed
相关产品推荐
相关产品推荐

