Reputation: 31
i am new to Python. i want reverse a string's words without reversing the whole string. And words which are repeating should not get reversed.
i want something like this-
Input- Dom is an artist, Dom lives in UK. Output- Dom si na tsitra, Dom sevil ni KU.
Upvotes: 0
Views: 1323
Reputation: 5384
You can use str.split which will create a list containing each word and collections.Counter to easily count each word in that list.
from string import punctuation # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
from collections import Counter
def reverse_text(text):
punc = ''
# remove any punctuation from end of text
while text[-1] in punctuation:
punc = text[-1] + punc
text = text[:-1]
# reverse text and add punctuation back on
return text[::-1] + punc
inp = "Dom is an artist, Dom lives in UK"
words = inp.split() # split input
counter = Counter(words) # count each word. Note: counts exact matches.
# rejoin the string reversing any unique words
res = ' '.join( reverse_text(word) if counter[word] == 1 else word for word in words )
print(res)
# Output
Dom si na tsitra, Dom sevil ni KU
Upvotes: 2
Reputation: 215
You just need the Counter package to count the number of each unique word in your sentence. You will then loop through your string and see if the word's count equals 1, in that case you reverse the word, other wise you just leave it the way it is. you will then append each resulting item to an emptey list and join them with space (i.e. ' '.join)
from collections import Counter
your_string = "Dom is an artist, Dom lives in UK"
lst = []
counts = Counter(your_string.split())
for i in your_string.split():
if counts[i]==1:lst.append(i[::-1])
else: lst.append(i)
' '.join(i for i in lst)
Upvotes: 1