当前路径下有一个文本文件article.txt,是一篇英文文章。写一个程序,将每一个句子的第一个单词全部变为大写字母,并且每一个句子单独变为一个段落,新文件保存到new_article.txt中(以.作为句子的分隔标记。)
实现代码如下,望采纳
# 读取文件
with open('article.txt', 'r') as f:
text = f.read()
# 使用.作为句子的分隔标记,将文本拆分成句子
sentences = text.split('.')
# 对每个句子的第一个单词进行大写字母处理
for i, sentence in enumerate(sentences):
words = sentence.split()
if len(words) > 0:
words[0] = words[0].upper()
sentences[i] = ' '.join(words)
# 将处理后的句子拼接成新的文本
new_text = '\n\n'.join(sentences)
# 将新文本写入新文件
with open('new_article.txt', 'w') as f:
f.write(new_text)
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!