【问题标题】:Load .txt files in Pandas DataFrame with separator line in between text.在 Pandas DataFrame 中加载 .txt 文件,并在文本之间添加分隔线。
【发布时间】:2018-07-27 12:51:24
【问题描述】:

我有一个包含如下文本的文本文件:

--------------------------------
I hate apples and love oranges.
He likes to ride bike.
--------------------------------

--------------------------------
He is a man of honour. 
She loves to travel.
--------------------------------

我想在 pandas 数据框中加载这个 txt 文件,并且每一行只包含分隔符之间的内容。例如:

第 1 行应该是这样的: 我讨厌苹果,喜欢橘子。 他喜欢骑自行车。

第 2 行应该是这样的: 他是个有尊严的人。 她喜欢旅行。

【问题讨论】:

  • 你尝试了什么?

标签: python pandas dataframe text separator


【解决方案1】:

看来您需要对文本进行预处理。

试试:

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.

【讨论】:

    猜你喜欢
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2021-06-04
    • 2021-05-14
    相关资源
    最近更新 更多