【问题标题】:How to split sentences written in an excel sheet in python?如何在python中拆分excel表格中写的句子?
【发布时间】:2018-05-02 16:46:28
【问题描述】:

我有这张excel表格:

enter image description here

我想从第一个 excel 表中制作另一个这样的 excel 表:

enter image description here

这是拆分单个句子的python代码,但我无法使用excel表进行拆分。

    import xlrd
    import pandas as pd
    b=xlrd.open_workbook("sample_docu5.xlsx")
    p=b.sheet_by_index(0)
    #open("sample_docu5.xlsx") as f:
    s=  "Dead poet society, Julia Roberts, London"
    line=s.split(',')
    print (line)

输出:

['Dead poet society', ' Julia Roberts', ' London']

【问题讨论】:

    标签: python excel split


    【解决方案1】:

    使用 Pandas,您可以读取 excel 文件,拆分列,将它们存储在 pandas 数据框中,将该数据框写入新的 excel 文件。

    import pandas as pd
    #Read in your dataset with the 2 headers
    df = pd.read_excel(r'sample_docu5.xlsx')
    
    #Split out the first column into 3 different columns
    df['Title'], df['Actor'],df['Place'] = df['All'].str.split(',', 2).str
    
    #Delete the 'All' column as we have created 3 new columns
    del df['All']
    
    #Reorder the columns
    df = df[['Title','Actor','Place','Document_Source']]
    df.to_excel('output.xlsx')
    df.head()
    

    【讨论】:

    • 作用是什么:del df['All']
    • 它删除存储在 1 列中的 ['Dead Poet Society', 'Julia Roberts', 'London'] 的 1 列。但是上面的代码将该列拆分为 3 列
    • 您能告诉我我应该如何对您提供的代码进行哪些更改以获得所需的输出?请参阅我提供的 2 个屏幕截图。
    • 使用我提供的代码,在 pandas 中创建数据框便于操作
    猜你喜欢
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    相关资源
    最近更新 更多