Как удалить пробелы в слове с помощью Python? - PullRequest
1 голос
/ 26 апреля 2019

Это ввод данных John plays chess and l u d o. Я хочу, чтобы вывод был в этом формате (указан ниже)

John plays chess and 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

Ответы [ 2 ]

2 голосов
/ 29 апреля 2019

Это должно работать!По сути, решение извлекает отдельные символы из предложения, превращает его в слово и присоединяет его к оставшемуся предложению.

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
0 голосов
/ 30 апреля 2019

Выше код не будет поддерживать последовательность слов при решении проблемы.Например, попробуйте ввести это предложение «Джон играет в шахматы и лудо»

Попробуйте использовать это вместо этого, если у вас есть одно слово с пробелами в тексте в любой позиции:

sentence = "John plays c h e s s and ludo"
sentence_list = sentence.split()
index = [index for index, item in enumerate(sentence_list) if len(item) == 1]
join_word = "".join([item for item in sentence_list if len(item) == 1])
if index != []:
    list(map(lambda x: sentence_list.pop(index[0]), index[:-1]))
    sentence_list[index[0]] = join_word
    sentence = " ".join(sentence_list)
else:
    sentence
...