Is there another to have exception for capitalizing an entire sentence. I've heard of skipList method, but it didn't work for my code. See below:
string = input('Enter a string: ')
i = 0
tempString = ' '.join(s[0].upper() + s[1:] for s in string.split(' '))
result = ""
for word in tempString.split():
if i == 0:
result = result + word + " "
elif (len(word) <= 2):
result = result + word.lower() + " "
elif (word == "And" or word == "The" or word == "Not"):
result = result + word.lower() + " "
else:
result = result + word + " "
i = i + 1
print ("\n")
print (result)
Sure. Write a complete list of words that should not be title-cased ("and", "the", "or", "not", etc), and title-case everything else.
words = s.split(' ')
result = ' '.join([words[0]] + [w.title() for w in words[1:] if w not in skipwords])
of course this will still miss Mr. Not's last name, which should be capitalized, and some stranger things like "McFinnigan" will be wrong, but language is hard. If you want better than that, you'll probably have to look into NTLK.
You could rewrite this like this
skip_words = {w.capitalize(): w for w in 'a in of or to and for the'.split()}
words = string.title().split()
result = ' '.join(skip_words.get(w, w) for w in words).capitalize()
Related
I came across below mentioned scenario:
Input:-
parselTongue
Expected Output:-
parsel_tongue
My code:-
empty_string = ""
word = input()
if word.islower() == 1:
empty_string = empty_string + word
print(empty_string)
else:
for char in word:
char = str(char)
if char.isupper() == 1:
x = char
y = word.find(x)
print(char.replace(char, word[0:y] + "_" + char.lower() + word[y:]))
My output:-
parsel_tTongue
Please advice where i am going wrong as my output is coming as "parsel_tTongue" and not "parsel_tongue"
The more elegant solution would be just to implement the logic using comprehension.
word = input()
output= ''.join(c if not c.isupper() else f'_{c.lower()}' for c in word)
#output: 'parsel_tongue'
I believe that this approach could be better.
It prevents from situations where word contains not only letters but also special characters or numbers.
word = "camelCaseWord"
res = "" # sanke case word
# handle 1st upper character
if word[0].isupper():
word = word[0].lower() + word[1:]
for w in word:
# Only letter can be upper
if w.isupper():
res += "_" + w.lower()
else:
res += w
print(res)
>>> camel_case_word
if word = "camelCase3Wor& - > >>> camel_case3_wor&
no need for loop use regex
import re
name = 'parselTongue'
name = re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
print(name) # camel_case_name
Adjust the slice on word
empty_string = ""
word = input()
if word.islower() == 1:
empty_string = empty_string + word
print(empty_string)
else:
for char in word:
char = str(char)
if char.isupper() == 1:
x = char
y = word.find(x)
print(char.replace(char, word[0:y] + "_" + char.lower()+ word[y+1:]))
prints the following for the input parselTongue
praselTongue
prasel_tongue
The best practice may be using regex:
fooBarBaz -> foo_bar_baz
re.sub(r'([A-Z])',lambda match:'_'+match.group(1).lower(),'fooBarBaz')
foo_bar_baz -> fooBarBaz
re.sub(r'_([a-z])',lambda match:match.group(1).upper(),'foo_bar_baz')
import re
camel_case = 'miaBau'
snake_case = re.sub(r'([A-Z])', r'_\1', camel_case).lower()
Despite this fill-in-the-blank script working successfully, I am unsure of how to randomly assign blanks. As can be seen, I placed two blanks between 5-7. However, I would like to randomize where they're set.
sentence = """Immigration is an issue that affects all residents of the United States, regardless of citizenship status"""
sentence0 = sentence.split(" ")
max = len(sentence)
sentence1 = sentence0[0:5]
sentence1 = " ".join(sentence1)
sentence2 = sentence0[7:max]
sentence2 = " ".join(sentence2)
Overall = sentence1 + " _ _ " + sentence2
print(Overall)
test = input()
Overall2 = sentence1 + " " + test + " " + sentence2
print(Overall2)
start = "\033[1m"
end = "\033[0;0m"
if Overall2 == sentence:
print(start + "Correct" + end)
else:
print(start + "Incorrect" + end)
This is simple and is working :
import random
sentence = "Immigration is an issue that affects all residents of the United States, regardless of citizenship status"
words = sentence.split(" ")
#SELECT RANDOM WORD FOR PLACING BLANK
rand_index = random.randint(0, len(words)-1)
#KEEP A BACKUP OF THE WORD
word_blanked = words[rand_index]
#REPLACE WORD WITH BLANK
words[rand_index] = "_____"
#MAKE BLANKED SENTENCE AND CORRECT ANSWER
blanked_sentence = ""
correct_answer = ""
for word in words:
blanked_sentence = blanked_sentence + word + " "
if word == "_____":
correct_answer = correct_answer + word_blanked + " "
else:
correct_answer = correct_answer + word + " "
print(blanked_sentence)
answer = input("Enter your answer : ")
if answer == word_blanked:
print("Correct Answer!")
else:
print("Wrong Answer!")
print("Correct Answer is : ")
print(correct_answer)
Something like this:
import random
sentence = """Immigration is an issue that affects all residents of the United States, regardless of citizenship status"""
sentence0 = sentence.split(" ")
# removed overlap with "max"
max_length = len(sentence0)
# generate a random slice based on the length of the sentence.
random_slice = random.randrange(0, max_length)
sentence1 = sentence0[0:random_slice ]
sentence1 = " ".join(sentence1)
# increment two words forward from the random slice
sentence2 = sentence0[random_slice + 2: max_length]
sentence2 = " ".join(sentence2)
Overall = sentence1 + " _ _ " + sentence2
print(Overall)
test = input()
Overall2 = sentence1 + " " + test + " " + sentence2
print(Overall2)
start = "\033[1m"
end = "\033[0;0m"
if Overall2 == sentence:
print(start + "Correct" + end)
else:
print(start + "Incorrect" + end)
Generic example:
import random
sentence = 'The quick brown fox jumps over the lazy dog'
# convert sentence from string to list
sentenceList = sentence.split(' ')
# get random location of the element to be replaced
locToReplace = random.randrange(0, len(sentenceList))
# replace with blanks
sentenceList[locToReplace] = '_ _'
# convert back to string
updatedSentence = ' '.join(sentenceList)
print(updatedSentence)
I'm trying to solve a problem that can be found in the Book The Coder's Apprentice by Pieter Spronck, in section 13.2.4. This is the code I wrote so far:
english_dutch = {"last":"laatst", "week":"week", "the":"de", "royal":"koninklijk",
"festival":"feast", "hall":"hal", "saw":"zaag", "first":"eerst", "performance":"optreden",
"of":"van", "a":"een", "new":"nieuw", "symphony":"symphonie", "by":"bij",
"one":"een", "world":"wereld", "leading":"leidend", "modern":"modern",
"composer":"componist", "composers:componisten" "two":"twee", "shed":"schuur", "sheds":"schuren"}
text = "Last week The Royal Festival Hall saw the first \
performance of a new symphony by one of the world's leading \
modern composers, Arthur 'Two-Sheds' Jackson."
def clean(t):
t = t.lower()
t = t.split()
new_t = ""
for word in t:
new_word = ""
for letter in word:
if "a" <= letter <= "z":
new_word += letter
if letter == "-":
new_word += " "
else:
continue
new_t += new_word + " "
return new_t
def translate(t):
translation = ""
for word in t.split():
if english_dutch.get(word):
translation += english_dutch[word] + " "
else:
translation += word + " "
return translation
def auto_correct():
news = ""
a = translate(clean(text)).split()
for word in a:
if len(word) > 1:
news += word + " "
print(news)
auto_correct()
It seems to work OK, but when I run it, the words "composers" and "two" are not translated.
You forgot a comma between the word composers and the word two. In addiotion you wrote "composers:componisten" instead of "composers":"componisten". Change your dictionary like so
english_dutch = {"last":"laatst", "week":"week",
"the":"de", "royal":"koninklijk",
"festival":"feast", "hall":"hal",
"saw":"zaag", "first":"eerst",
"performance":"optreden",
"of":"van", "a":"een",
"new":"nieuw", "symphony":"symphonie",
"by":"bij",
"one":"een", "world":"wereld",
"leading":"leidend", "modern":"modern",
"composer":"componist",
"composers":"componisten", "two":"twee", # <- HERE
"shed":"schuur", "sheds":"schuren"}
Why it passed undetected? Check this:
>>> {"composers:componisten" "two":"twee"}
{'composers:componistentwo': 'twee'}
Because the comma was missing and the colon was within the string, python concatenated the strings, creating a useless (but valid) key/value pair.
This behaviour is documented here
Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld".
I want to remove extra spaces in a string using only for/while loops, and if statements; NO split/replace/join.
like this:
mystring = 'Here is some text I wrote '
while ' ' in mystring:
mystring = mystring.replace(' ', ' ')
print(mystring)
output:
Here is some text I wrote
Here's what I tried. Unfortunately, it doesn't quite work.
def cleanupstring(S):
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
lasti = i
result += i
print(result)
cleanupstring("Hello my name is joe")
output:
Hello my name is joe
My attempt doesn't remove all the extra spaces.
Change your code to this:
for i in S:
if lasti == " " and i == " ":
i = ""
else:
lasti = i
result += i
print(result)
Check that the current character and the next one are spaces, and if not, add them to a clean string. There really is no need for an and in this case, since we are comparing to the same value
def cleanWhiteSpaces(str):
clean = ""
for i in range(len(str)):
if not str[i]==" "==str[i-1]:
clean += str[i]
return clean
Uses the end of result in place of lasti:
def cleanupstring(S):
result = S[0]
for i in S[1:]:
if not (result[-1] == " " and i == " "):
result += i
print(result)
cleanupstring("Hello my name is joe")
Just try this
t = "Hello my name is joe"
" ".join(t.split())
this will output
"Hello my name is joe"
I'm trying to write a function that will translate the input into so-called "cow Latin." I want to return the values from the if statement but whenever I do I get a syntax error. I can print the value but I want to avoid the function returning None as well.
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!##$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
print('{0}moo'.format(cow_word), end=' ')
else:
cow_word = sentence_list[i][1:] + sentence_list[i][:1]
print('{0}oo'.format(cow_word), end=' ')
cow_latin = cow_latinify_sentence("the quick red fox")
print(cow_latin)
In short, how can I get the function to return instead of print?
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!##$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
result = ''
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
result += ('{0}moo'.format(cow_word) + ' ')
else:
result += '{0}oo'.format(sentence_list[i][1:] + sentence_list[i][:1]) + ' '
return result.strip()
>>> cow_latinify_sentence('hello there i am a fish')
'ellohoo heretoo imoo ammoo amoo ishfoo'
Why not just replace the two instances of
print('{0}moo'.format(cow_word), end=' ')
with
return '{0}moo'.format(cow_word)+' '
You have to get rid of end=; you don't have to replace the newline that would otherwise follow the output of print, but if you want a space at the end of the returned string you still have to append it yourself.
You need to create a list to accumulate your results.
result = []
your two print statements in your function would need changed to result.append(XXXX). Then when you have processed the entire sentence you can
return (result)
or, to re-form it into a sentence:
return " ".join(result) + '.'
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!##$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
result = ''
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
result += '{0}moo'.format(cow_word) + ' '
else:
result += '{0}oo'.format(sentence_list[i][1:] + sentence_list[i][:1]) + ' '
return result.strip()