亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將文本文件中的數據提取到定義為空白行之間的數據行的句子中?

如何將文本文件中的數據提取到定義為空白行之間的數據行的句子中?

子衿沉夜 2023-10-05 16:30:17
數據位于文本文件中,我想將其中的數據分組為句子。句子的定義是所有行依次排列,每行至少有 1 個字符。包含數據的行之間有空白行,因此我希望空白行標記句子的開頭和結尾。有沒有辦法通過列表理解來做到這一點?文本文件中的示例。數據看起來像這樣:This is thefirst sentence.This is a really long sentenceand it just keeps going across manyrows there will not necessarily be punctuationor consistency in word lengththe only difference in ending sentenceis the next row will be blankhere would be the third sentenceas you seethe blanks between rows of data help define what a sentence isthis would be sentence 4i want to pull datafrom text fileas such (in sentences) where sentences are defined withblank records in betweenthis would be sentence 5 since blank row above itand continues but ends because blank row(s) below it
查看完整描述

2 回答

?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

您可以使用 . 獲取整個文件作為單個字符串file_as_string = file_object.read()。由于您想將此字符串拆分為空行,這相當于拆分兩個后續換行符,因此我們可以這樣做sentences = file_as_string.split("\n\n")。最后,您可能想要刪除句子中間仍然存在的換行符。您可以通過列表理解來做到這一點,將換行符替換為空:sentences = [s.replace('\n', '') for s in sentences]


總共給出:


file_as_string = file_object.read()

sentences = file_as_string.split("\n\n")

sentences = [s.replace('\n', '') for s in sentences]


查看完整回答
反對 回復 2023-10-05
?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

為此,您可以非常有效地使用正則表達式拆分。

如果您只想用雙空格分隔,請使用:

^[ \t]*$

演示

在Python中,你可以這樣做:

import re   


with open(fn) as f_in:

    sentencences=re.split(r'\r?\n^[ \t]*$', f_in.read(), flags=re.M)

如果要刪除\n文本中的單個內容:


with open(fn) as f_in:

    sentencences=[re.sub(r'[ \t]*(?:\r?\n){1,}', ' ', s) 

         for s in re.split(r'\r?\n^[ \t]*$', f_in.read(), flags=re.M)]


查看完整回答
反對 回復 2023-10-05
  • 2 回答
  • 0 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號