簡體   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