简体   繁体   中英

Python 3 - How to capitalize first letter of every sentence when translating from morse code

I am trying to translate morse code into words and sentences and it all works fine... except for one thing. My entire output is lowercased and I want to be able to capitalize every first letter of every sentence.

This is my current code:

 text = input()
        if is_morse(text):
            lst = text.split(" ")
            text = ""
            for e in lst:
                text += TO_TEXT[e].lower()
            print(text)

Each element in the split list is equal to a character (but in morse) NOT a WORD. 'TO_TEXT' is a dictionary. Does anyone have a easy solution to this? I am a beginner in programming and Python btw, so I might not understand some solutions...

From what is understandable from your code, I can say that you can use the title() function of python. For a more stringent result, you can use the capwords() function importing the string class.

This is what you get from Python docs on capwords:

Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.

Maintain a flag telling you whether or not this is the first letter of a new sentence. Use that to decide whether the letter should be upper-case.

text = input()
if is_morse(text):
    lst = text.split(" ")
    text = ""
    first_letter = True
    for e in lst:
        if first_letter:
            this_letter = TO_TEXT[e].upper()
        else:
            this_letter = TO_TEXT[e].lower()

        # Period heralds a new sentence. 
        first_letter = this_letter == "."  

        text += this_letter
    print(text)

Suppose you have this text :

text = "this is a sentence. this is also a sentence"

You can upper-case the first letter of each sentence by doing:

  1. Split text on '.' characters
  2. Remove whitespace from the beginning and end of each item
  3. Capitalize the first letter of each item
  4. Rejoin the items with '. ' '. '

In step-by-step code:

  originals  = text.split('.')
  trimmed    = [ sentence.strip() for sentence in originals ]
  uppercased = [ sentence[0].upper() + sentence[1:] for sentence in trimmed ]
  rejoined   = '. '.join(uppercased)

You'll want to pack this into a function. Creating all those intermediate list objects is not necessary, you can do it with for loops or generators .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM