将文本中句子的第一个单词大写

ajs*_*stc 2 python string split capitalize

我想确保文本中的每个句子都以大写字母开头。

例如,“我们有关于你们派往我们世界的使者的好消息和坏消息,”外星人大使告诉总理。好消息是它们尝起来像鸡肉。”应该变成

“我们有关于你们派往我们世界的使者的好消息和坏消息,”外星人大使告诉总理。好消息是它们尝起来像鸡肉。”

我尝试使用 split() 来分割句子。然后,我将每行的第一个字符大写。我将字符串的其余部分附加到大写字符后。

  text = input("Enter the text: \n")
  lines = text.split('. ') #Split the sentences

  for line in lines:
      a = line[0].capitalize() # capitalize the first word of sentence
      for i in range(1, len(line)):
           a = a + line[i] 
      print(a)
Run Code Online (Sandbox Code Playgroud)

我想知道“我们有关于你们派往我们世界的使者的好消息和坏消息”,外星人大使告诉总理。好消息是它们尝起来像鸡肉。”

我得到“关于你们来到我们世界的使者的好消息和坏消息”,外星大使告诉总理,好消息是它们尝起来像鸡肉。

Xte*_*ven 5

这段代码应该可以工作:

text = input("Enter the text: \n")
lines = text.split('. ')  # Split the sentences

for index, line in enumerate(lines):
    lines[index] = line[0].upper() + line[1:]
print(". ".join(lines))
Run Code Online (Sandbox Code Playgroud)

代码中的错误是str.split(chars)删除了分割分隔符char,这就是删除句点的原因。

抱歉没有提供完整的描述,因为我不知道该说什么。请随时在评论中提问。

编辑:让我尝试解释一下我做了什么。

  • 第 1-2 行:接受输入并按 拆分为列表'. '。在示例输入上,这给出:['"We have good news and bad news about your emissaries to our world," the extraterrestrial ambassador informed the Prime Minister', 'the good news is they tasted like chicken.']。请注意,句号从被分割的第一个句子中消失了。
  • 第 4 行:enumerate是一个生成器,并迭代一个迭代器,返回 .a 中迭代器中每个项目的索引和项目tuple
  • line第 5 行:将in的位置替换lines为第一个字符的大写加上该行的其余部分。
  • 第 6 行:打印消息。". ".join(lines)基本上扭转了你对 split 所做的事情。str.join(l)接受一个字符串迭代器 ,l并将它们粘str在所有项目之间。如果没有这个,你就会错过月经。