2014-11-18 5 views
0

У меня есть следующая строка:Python: Как удалить определенные слова в строке

right then the treasure be right on that island right where we left it then when ye left me

Моя задача состоит в том, чтобы удалить все, кроме повторяющихся слов. Таким образом, результат будет:

>>>right right then left

мне удалось получить следующий вывод:

>>>['right', 'then', 'the', 'treasure', 'be', 'on', 'that', 'island', 'where', 'we', 'left', 'it', 'when', 'ye', 'me']

Теперь, если я смог удалить вышеупомянутые слова из исходной строки, я буду оставил правильный выход. Как мне это сделать?

+1

В этом смысле ваш выход должен быть: - справа направо вправо слева, а затем. Я прав ? –

ответ

1

Используйте Counter:

from collections import Counter 
words = Counter('right then the treasure be right on that island right where we left it then when ye left me') 
for word, count in words.most_common(): 
    if count > 1: 
     print word, 
+0

Желаемый результат - «справа налево», который неясен, и в нем должно быть включено все событие или только один раз. –

0

Это даст желаемый результат, выводя список всех вхождений слов, которые имеют счетчик> 1 в строке

your_string = 'right then the treasure be right on that island right where we left it  then when ye left me' 
words = your_string.split() 
words_that_occur_more_than_once = [word for word in words if words.count(word)>1] 
words_that_occur_more_than_once.sort(reverse=True) 
print(' '.join(words_that_occur_more_than_once)) 

Это будет закажите строку так, как вы этого хотите. Я не понимаю, почему на выходе должно быть меньше «правильного» слова.

+1

Когда я запускаю ваш код в Python 3.4.1, он дает следующую ошибку: print (words_that_occur_more_than_once.join ('')) AttributeError: объект «list» не имеет атрибута «join». – SSC

+1

Должно быть '' '.join (words_that_occur_more_than_once) ' – Hamatti

+0

Это дает мне результат: справа и справа справа, а затем слева Выход должен быть: справа и слева – user3036519

0

Сначала создайте метод, чтобы определить, отображается ли строка более одного раза. Затем используйте этот метод, чтобы извлечь нужные слова, а затем перепечатайте.

# Method returns True if the searchWord is in the text only once. 
# Returns False otherwise. 
def occursOnlyOnce(searchWord, text): 
    count = 0 
    words = text.split(); 
    for word in words: 
     if word == searchWord: 
      count += 1 

    if count == 1: 
     return True 
    else: 
     return False 


# Initial input text. 
initialText = "right then the treasure be right on that island right where we left it then when ye left me" 

# Split words into a list. 
words = initialText.split(); 

# List of recurring words only. 
finalWords = [] 

# Extract words that don't appear once, and place into a list. 
for word in words: 
    if not occursOnlyOnce(word, initialText): 
     finalWords.append(word) 

# Assemble a space-delimited string containing the words. 
finalStr = " ".join(finalWords) 

# Print out the words that occur more than once. 
print(finalStr) 
+0

: O Даже в ассемблере у нас может быть меньше кода для такой тривиальной задачи. – Alvaro

+2

Для новичков легче понять код, который разбит на более мелкие логические шаги и хорошо комментируются. – Ryan

+0

Вы правы ... но все же .. это python, а не java или c .. – Alvaro

0

Этот код полностью удалит все и удалит лишние пробелы.

def removePhrase(string, charArray): 

    string = str(string) 
    text = string.split() 

    for x in range (0, len(text)): 
     for y in range (0, len(charArray)): 
      if text[x] == charArray[y]: 
       text[x] = text[x].replace(charArray[y], "") 

    text = " ".join(text) 
    return text 

string = "right then the treasure be right on that island right where we left it then when ye left me" 
text = string.split() 
charArray = [word for word in text if text.count(word)<2] 
print(charArray) 
finalString = removePhrase(string, charArray) 
finalString = ' '.join(finalString.split()) 
print(finalString) 
+0

Это некрасиво :( – Alvaro

+0

Mine возвращает «справа, а затем направо вправо, а затем влево». –

Смежные вопросы