代码之家  ›  专栏  ›  技术社区  ›  Harshit Singh

在pandas数据框中加载.txt文件,文本之间有分隔线。

  •  0
  • Harshit Singh  · 技术社区  · 6 年前

    我有文本文件,其中包含如下文本:

    --------------------------------
    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行应类似于: 他是个有荣誉感的人。 她喜欢旅行。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Rakesh    6 年前

    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.