【问题标题】:Python add a space between special characters and wordsPython在特殊字符和单词之间添加空格
【发布时间】:2017-01-04 14:28:52
【问题描述】:

我正在从事一个数据科学项目,但我遇到了一个问题。我有一个充满字符串的数组,如下面的字符串,我想在单词之间和特殊字符之间添加一个空格

sentence[i] = 'This is a⓵⓶⓷string'

我期待这样的事情:

sentence[i] = 'This is a ⓵ ⓶ ⓷ string'

我的最后一次尝试:

l=[]
for i in lines:
    for j in i:
        if j.isalpha() == False:
            l.append(i.split())
        else:
            l.append(i)

print(l)

for i in l:
    s = ' '.join(i)

【问题讨论】:

  • 你试过解决这个问题吗?
  • 是的,使用拆分连接方法,但对我来说太难了......
  • 与其他 unicode 字符我没有这个问题
  • 为什么我又投了反对票???
  • 你能显示你试过的代码吗?也许这就是为什么有人反对

标签: python string join split


【解决方案1】:

您可以简单地扫描整行并有选择地为每个既不是字母也不是空格的字符添加空格。

s = 'This is a⓵⓶⓷string'
t = ''
for x in s :
    if not str.isalpha(x) and x != ' ' :
        if t[-1] != ' ':
            t+= ' '
        t += x
        t += ' '
    else: t += x

这适用于你给出的例子。

【讨论】:

    【解决方案2】:

    使用regular expressions 完成该任务,特别是re.sub 和一个反向引用,以便用空格包围匹配的字符。

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 2019-06-06
      • 2011-04-28
      • 2018-12-01
      • 1970-01-01
      相关资源
      最近更新 更多