![](/img/trans.png)
[英]Pandas parsing text files with different signs for change line and separator
[英]Load .txt files in Pandas DataFrame with separator line in between text.
我有包含如下文本的文本文件:
--------------------------------
I hate apples and love oranges.
He likes to ride bike.
--------------------------------
--------------------------------
He is a man of honour.
She loves to travel.
--------------------------------
我想將此txt文件加載到pandas數據框中,並且每行僅包含分隔符之間的內容。 例如:
第1行應為:我討厭蘋果,也喜歡橙子。 他喜歡騎自行車。
第2行應為:他是一個榮譽人物。 她喜歡旅行。
看起來您需要預處理文本。
嘗試:
import pandas as pd
res = []
temp = []
with open(filename) as infile:
for line in infile:
val = line.strip()
if val:
if not val.startswith("-"):
temp.append(val)
else:
if temp:
res.append(" ".join(temp))
temp = []
df = pd.DataFrame(res, columns=["Test"])
print(df)
輸出:
Test
0 I hate apples and love oranges. He likes to ri...
1 He is a man of honour. She loves to travel.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.