Python按关键词分割文本并存入单个单元格的实现方法
基于关键词分割文本并提取内容的解决方案
你的问题出在直接用固定字符串split("sample story")匹配——关键词存在大小写差异(比如Sample Story),还跟着数字和冒号,导致分割逻辑不准确。以下是可行的解决方法:
解决方案:用正则表达式实现灵活分割
利用Python的re模块,匹配不区分大小写的关键词格式,精准分割每个故事块:
import re # 你的待处理文本 contents = """sample story 1: This is another great story that teaches a lesson that’s written for kids but that adults can enjoy, too. The story tells of a grasshopper who lounges around all summer while his friend the ant prepares for the winter. When winter comes, the two friends end up in very different situations! The moral is that those who save up during good times will get to enjoy the benefits when times are bad. Sample Story 2: This very short story from India was originally written in Sanskrit (an ancient language). When a group of doves is caught in a hunter’s net, they must work together as a team to escape from the hunter’s clutches. You can listen to a reading of the story as you read along on this website. sample story 4: 1. This is a modern-day story about a little girl with a big secret she can’t tell anyone about. When her teacher finds out her secret, they work together to fix the issue. 2. This modern story is about a young woman named Penny who is anxious about going to her family’s annual reunion barbecue. But despite screaming children and arguing cousins, Penny ends up happy that she came to the reunion when she starts a conversation with a handsome man. Note: This story is a good choice for absolute beginners because it uses only the present tense. It’s also written in very basic English with simple vocabulary and short sentences.""" # 正则规则:不区分大小写匹配"sample story + 数字 + 冒号" story_sections = re.split(r'(?i)sample story \d+:', contents) # 清理无效内容,得到可直接存入单元格的片段 cleaned_sections = [section.strip() for section in story_sections if section.strip()] # 输出结果(每个元素对应一个单元格内容) for num, section in enumerate(cleaned_sections, 1): print(f"单元格 {num}:\n{section}\n")
关键说明:
(?i):让正则匹配不区分大小写,覆盖sample story和Sample Story两种写法;\d+:匹配任意长度的数字,适配1、2、4这类编号;strip():清理每个片段首尾的换行、空格,过滤分割后产生的空字符串;- 最终
cleaned_sections列表中的每个元素,就是可以单独存入单元格的内容。
内容的提问来源于stack exchange,提问作者sayile firahs
相关产品推荐
相关产品推荐

