You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中去除字符串字母间多余空格并提取有效文本?

格式异常字符串修复方案

核心处理逻辑

针对字符串中存在的字母间冗余空格、转义字符、无关特殊符号,分三步处理:

  1. 清除{、}、\[、\]、\n这类无关符号与转义字符
  2. 移除单个字母之间的空格,同时保留单词间的空格(单词间为连续两个空格,字母间为单个空格)
  3. 合并连续空格并清理首尾多余空格

Python代码实现

def fix_abnormal_string(abnormal_str):
    # 第一步:移除特殊符号和转义字符
    cleaned = abnormal_str.replace('{', '').replace('}', '').replace('\\[', '').replace('\\]', '').replace('\\n', '')
    # 第二步:消除单个字母间的空格
    import re
    cleaned = re.sub(r'(\w) (\w)', r'\1\2', cleaned)
    # 第三步:规整空格格式
    cleaned = re.sub(r'\s+', ' ', cleaned).strip()
    return cleaned

# 测试示例
abnormal_str = "{'\\[\\n M a k i n g   c o f f e e   i s   n o t   r e l a t e d   t o   t h e   c o n t e x t   i n f o r m a t i o n   p r o v i d e d .\\]'}"
print(fix_abnormal_string(abnormal_str))
# 输出:Making coffee is not related to the context information provided.

分步说明

  • 清理特殊符号:通过replace直接移除所有干扰性符号,还原字符串的核心文本部分
  • 合并字母:用正则(\w) (\w)匹配单个字母+空格+单个字母的模式,替换为字母拼接,精准消除字母间的冗余空格
  • 规整空格:用\s+匹配所有连续空格并替换为单个空格,再用strip()清理首尾空格,得到格式标准的文本

简化版实现

import re

abnormal_str = "{'\\[\\n M a k i n g   c o f f e e   i s   n o t   r e l a t e d   t o   t h e   c o n t e x t   i n f o r m a t i o n   p r o v i d e d .\\]'}"
normal_str = re.sub(r'(\w) (\w)', r'\1\2', re.sub(r'[{}[\]\\n]', '', abnormal_str))
normal_str = re.sub(r'\s+', ' ', normal_str).strip()
print(normal_str)

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 20:43:30