python - 如何使用python删除单词中的空格?

标签 python python-3.x text-mining spacy removing-whitespace

这是给定的输入 John play chess and l u do o. 我希望输出采用这种格式(如下所示)

John 下国际象棋和 ludo。

我已经尝试使用正则表达式来删除空格 但对我不起作用。

import re
sentence='John plays chess and l u d o'
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)

print(sentence)

我期望输出 John plays chess and ludo. .
但是我得到的输出是 Johnplayschessandludo

最佳答案

这应该有效!从本质上讲,该解决方案从句子中提取单个字符,使其成为一个单词,然后将其连接回剩余的句子。

s = 'John plays chess and l u d o'

chars = []
idx = 0

#Get the word which is divided into single characters
while idx < len(s)-1:

    #This will get the single characters around single spaces
    if s[idx-1] == ' ' and s[idx].isalpha() and s[idx+1] == ' ':
        chars.append(s[idx])

    idx+=1

#This is get the single character if it is present as the last item
if s[len(s)-2] == ' ' and s[len(s)-1].isalpha():
    chars.append(s[len(s)-1])

#Create the word out of single character
join_word = ''.join(chars)

#Get the other words
old_words = [item for item in s.split() if len(item) > 1]

#Form the final string
res = ' '.join(old_words + [join_word])

print(res)

输出看起来像

John plays chess and ludo

关于python - 如何使用python删除单词中的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55864233/

相关文章:

python - wsgi.py 丢失,manage.py 存在

python - 异步初始化时将参数传递给 python 类

Python Regex - 在文本文件中的(多个)表达式之间提取文本

python - PostgreSQL 模式和无效的一对多关系的 Alembic 迁移问题

python - 使用 Python 检索图像描述(不通过 PIL 或 exifread 在 EXIF 数据中返回)

Python LASSO 最大非零系数个数

python - 软件包的 pip 安装可以从源代码安装,但从软件包安装失败

python - 如何提取数字之间的字符串? (并保留字符串中的第一个数字?)

algorithm - 开发算法来分析单词

javascript - 使用 Ajax 的 Django POST