[英]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.
“ TO_TEXT”是字典。 Does anyone have a easy solution to this?
有人对此有一个简单的解决方案吗? I am a beginner in programming and Python btw, so I might not understand some solutions...
我是编程和Python btw的初学者,所以我可能不理解某些解决方案...
From what is understandable from your code, I can say that you can use the title()
function of python. 从您的代码可以理解的角度来看,可以说您可以使用python的
title()
函数。 For a more stringent result, you can use the capwords()
function importing the string
class. 为了获得更严格的结果,您可以使用
capwords()
函数导入string
类。
This is what you get from Python docs on capwords: 这是您从关于关键词的Python文档中获得的:
Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join().
使用str.split()将参数分解为单词,使用str.capitalize()将每个单词大写,然后使用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.
如果不存在可选的第二个参数sep或“无”,则将空白字符替换为一个空格,并删除前导和尾随空白,否则使用sep分隔和合并单词。
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
:
text = "this is a sentence. this is also a sentence"
You can upper-case the first letter of each sentence by doing: 您可以通过以下操作将每个句子的首字母大写:
text
on '.'
'.'
上分割text
characters '. '
'. '
加入项目'. '
'. '
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
. 不必创建所有这些中间
list
对象,可以使用for
循环或generators
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.