如何在段落中每N个单词后添加子串分隔符
实现每N个单词后添加分隔符的技术方案
这里有几个简单易懂的方案来实现你要的「每N个单词后添加$$$$分隔符」的需求,不管你用Python还是JavaScript都能轻松搞定:
核心思路
- 先把原始段落按空格分割成一个个"单词"(这里的单词包含原段落里的标点,比如
industry.会被当作一个整体,保持原文格式) - 把分割后的单词列表按每N个为一组进行分组
- 每组内的单词用空格拼接,再用
$$$$把所有组连接起来,就得到了目标文本
Python 实现
def add_separator(paragraph, n, separator="$$$$"): # 按空格分割段落为单词列表 words = paragraph.split() grouped_words = [] # 每n个单词为一组处理 for i in range(0, len(words), n): # 取出当前组的单词并拼接成字符串 group = ' '.join(words[i:i+n]) grouped_words.append(group) # 用分隔符连接所有组 return f" {separator} ".join(grouped_words) # 测试用例 original_paragraph = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." n_value = 3 print(add_separator(original_paragraph, n_value))
运行这段代码后,输出的文本就会按照每3个单词添加$$$$分隔符的格式呈现。
JavaScript 实现
如果你需要在前端或者Node.js环境中实现,这个方案同样适用:
function addSeparator(paragraph, n, separator = "$$$$") { // 按空格分割成单词数组 const words = paragraph.split(' '); const wordGroups = []; // 分组处理单词 for (let i = 0; i < words.length; i += n) { const group = words.slice(i, i + n).join(' '); wordGroups.push(group); } // 用分隔符连接所有组 return wordGroups.join(` ${separator} `); } // 测试用例 const originalParagraph = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; const nValue = 3; console.log(addSeparator(originalParagraph, nValue));
额外说明
上面的方案是按空格分割"单词",这样能最大程度保留原文的标点和格式。如果你需要更严格的单词定义(比如只提取纯字母数字的单词,忽略标点),可以用正则表达式来分割:
- Python中可以替换
split()为re.findall(r'\b\w+\b', paragraph) - JavaScript中可以替换
split(' ')为paragraph.match(/\b\w+\b/g)
不过要注意,这种方式会丢失原文的标点和部分格式,需要根据你的实际需求来选择。
内容的提问来源于stack exchange,提问作者Abdelahad Darwish
相关产品推荐
相关产品推荐

