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

依然范特西╮ 提交于 2021-02-08 07:48:57

问题


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...


回答1:


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)



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/40595150/python-3-how-to-capitalize-first-letter-of-every-sentence-when-translating-fro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!