检测并替换缩写:基于嵌套列表与字典的文本处理需求
问题描述
我有如下格式的嵌套列表:
Mylist = [["where is USA?", "How are you in UK?"], ["I need it", "OMG you scared me"]]
同时还有一个缩写映射字典:
Abbr = {"USA": "United States of America", "UK": "United Kingdom", "ASAP": "As soon as possible", "OMG": "Oh my god"}
需要遍历该嵌套列表,识别其中的缩写并进行替换,最终生成包含原句和替换后句子的新列表,预期结果如下:
[["where is USA?", "where is United States of America?", "How are you in UK?", "How are you in United Kingdom?"], ["I need it", "OMG you scared me", "Oh my god you scared me"]]
解决方案
通过嵌套遍历列表结合字符串替换即可实现需求,核心逻辑如下:
- 外层遍历嵌套列表的每个子列表
- 对每个句子,先将原句加入结果集合
- 检查句子中是否存在缩写字典内的缩写,若存在则替换并将新句子加入结果
实现代码:
# 原始嵌套列表 Mylist = [["where is USA?", "How are you in UK?"], ["I need it", "OMG you scared me"]] # 缩写映射字典 Abbr = {"USA": "United States of America", "UK": "United Kingdom", "ASAP": "As soon as possible", "OMG": "Oh my god"} # 初始化结果列表 processed_list = [] # 遍历每个子列表 for sublist in Mylist: temp_sublist = [] for sentence in sublist: # 添加原句到临时子列表 temp_sublist.append(sentence) # 遍历缩写字典,查找并替换 for abbr, full_form in Abbr.items(): if abbr in sentence: replaced_sent = sentence.replace(abbr, full_form) temp_sublist.append(replaced_sent) # 每个句子仅处理第一个匹配的缩写(符合示例逻辑) break processed_list.append(temp_sublist) # 输出处理后的列表 print(processed_list)
运行结果
执行代码后输出与预期完全一致:
[["where is USA?", "where is United States of America?", "How are you in UK?", "How are you in United Kingdom?"], ["I need it", "OMG you scared me", "Oh my god you scared me"]]
中文版本拓展
若需要将所有句子翻译成中文,可新增翻译映射并生成中文结果,示例代码如下:
# 示例句子中英文翻译映射 trans_map = { "where is USA?": "美国在哪里?", "where is United States of America?": "美利坚合众国在哪里?", "How are you in UK?": "你在英国过得怎么样?", "How are you in United Kingdom?": "你在大不列颠及北爱尔兰联合王国过得怎么样?", "I need it": "我需要它", "OMG you scared me": "我的天,你吓到我了", "Oh my god you scared me": "哦我的天,你吓到我了" } # 生成中文结果列表 chinese_result = [] for sublist in processed_list: chinese_sublist = [trans_map[sent] for sent in sublist] chinese_result.append(chinese_sublist) print(chinese_result)
运行后输出中文结果:
[["美国在哪里?", "美利坚合众国在哪里?", "你在英国过得怎么样?", "你在大不列颠及北爱尔兰联合王国过得怎么样?"], ["我需要它", "我的天,你吓到我了", "哦我的天,你吓到我了"]]
内容的提问来源于stack exchange,提问作者Rohan
相关产品推荐
相关产品推荐

