簡體   English   中英

在Pandas DataFrame中加載.txt文件,並在文本之間使用分隔線。

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM