Reputation: 327
I have problem with my code. In this example it should print out The Wind in the Willows
, but it does print The Wind In The Willows. I think the problem is that replace function does not execute. I have no idea what's wrong with this code. Please help.
PS. Basic idea of this function is to return title lookalike string with exception (minor_words
). Minor_words
should be lower case in a title (despite the case if minor_words
is the first word in the title
)
def title_case(title, minor_words):
exc = [x for x in title.lower().split() if x in minor_words.lower().split()]
for string in exc:
if title.split().index(string) == 0:
title = title.title()
else:
title = title.title().replace(string, string.lower())
return title
print (title_case('THE WIND IN THE WILLOWS', 'The In'))
Upvotes: 0
Views: 82
Reputation: 4287
def title_case(title, minor_words):
# lowercase minor_words and make a set for quicker lookups
minor_set = set(i for i in minor_words.lower().split())
# tokenize the title by lowercasing
tokens = title.lower().split()
# create a new title by capitalizing words that dont belong to minor_set
new_title = ' '.join(i if i in minor_set else i.capitalize() for i in tokens)
# Finally return the capitalized title.
if len(new_title) > 1:
return new_title[0].upper() + new_title[1:]
else:
# Since its just one char, just uppercase it and return it
return new_title.upper()
Output:
>>> print (title_case('THE WIND IN THE WILLOWS', 'The In'))
The Wind in the Willows
Upvotes: 2
Reputation: 3742
Since you assign to title
in the loop, you get the value of title is the same as the value assigned to it by the last time through the loop.
I've done this differently. I loop through all the words in the title (not just the exclusions) and title case those that are not excluded.
def title_case(title, minor_words):
"""Title case, excluding minor words, but including the first
word"""
exclusions = minor_words.lower().split()
words = title.split()
# Loop over the words, replace each word with either the title
# case (for first word and words not in the exclusions list)
# or the lower case (for excluded words)
for i, word in enumerate(words):
if i == 0 or word.lower() not in exclusions:
words[i] = words[i].title()
else:
words[i] = words[i].lower()
title = " ".join(words)
return title
print (title_case('THE WIND IN THE WILLOWS', 'The In'))
Upvotes: 1
Reputation: 714
for x in minor_words.split():
title = title.replace(x,x.lower())
I'm a little confused as to what exactly you are trying to do(its late for me so I can't think) but that will replace all words in title
that are minor_words
with a lower case copy. Making the first word capital can be done with title = title.title()[0]+title[1:]
Upvotes: 0