繁体   English   中英

如何在 python 中打印特定行数?

[英]How to print specific number of lines in python?

假设下面是 3 个句子的字符串

q="Widows and orphans occur when the first line of a paragraph is the last in a column or page, or when the last line of a paragraph is the first line of a new column or page.The function of a paragraph is to mark a pause, setting the paragraph apart from what precedes it. If a paragraph is preceded by a title or subhead, the indent is superfluous and can therefore be omitted."

如果用户想要第一句,它应该打印第一句。 如果用户想要 2 个句子,它应该打印开始 2 个句子

我已经使用 nltk 完成了此操作,但是否可以使用任何其他方法?

像 Aran-Fey 建议您可以使用 String.split() function 如下:

print(q.split("."))

并且可能会根据用户输入的内容添加条件。

基本上,拆分 function 创建一个字符串数组,并使用提供的参数将字符串分隔为数组的多个元素。

希望这可以帮助。

new_list = q.split(".")

现在你有 n 行的新列表,只是使用列表索引来打印特定的行

您可以使用 split() function

string.split()[:num]

例如

string="hello stack overflow"
print(string.split()[:2])

Output:['你好','堆栈']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM