【发布时间】:2020-05-03 06:32:17
【问题描述】:
说,字符串看起来像:
我喜欢馅饼。你喜欢苹果。我们喜欢橘子。
我将如何定义一个名为format_poem() 的函数,它基本上可以接受任何带有上述段落的输入,并将每个句子放在单独的行中?
我确定它位于每个句子之后的句点,但作为菜鸟,我无法理解它。这也用.split()方法吗?
感谢您的帮助。
【问题讨论】:
标签: python function methods split sentence
说,字符串看起来像:
我喜欢馅饼。你喜欢苹果。我们喜欢橘子。
我将如何定义一个名为format_poem() 的函数,它基本上可以接受任何带有上述段落的输入,并将每个句子放在单独的行中?
我确定它位于每个句子之后的句点,但作为菜鸟,我无法理解它。这也用.split()方法吗?
感谢您的帮助。
【问题讨论】:
标签: python function methods split sentence
使用.replace() 将句点替换为新行的字符(几乎普遍为\n)
def format_poem(paragraph):
return paragraph.replace('. ','\n')
【讨论】:
\n 是换行符,因此如果打印或写入文件,通常会导致输出分布在多行中。
你是对的:split 会做你需要的。
str = "I like pie. You like apples. We like oranges."
def format_poem(inStr):
t = inStr.split(". ")
return t
for el in format_poem(str):
print(el)
输出:
I like pie
You like apples
We like oranges.
或者,您可以打印函数内部的行,只需在函数内部移动 for 循环:
I like pie. You like apples. We like oranges.
def format_poem(inStr):
t = inStr.split(". ")
for el in t:
print(el)
为了保留句子末尾的句点,就像在原始字符串中一样,您需要使用replace()方法,搜索". "并替换为".\n"。请注意此方法如何不修改原始字符串:
#Perform replacement
str2 = str1.replace(". ", '.\n')
#Print the original string
print(str1)
#Print new string, result of the replacement
print(str2)
新的输出是:
#The original string
I like pie. You like apples. We like oranges.
#The newly assigned string
I like pie.
You like apples.
We like oranges.
【讨论】: