首页 > 解决方案 > 如何在python中拆分写在excel表格中的句子?

问题描述

我有这个excel表:

在此处输入图像描述

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

在此处输入图像描述

这是拆分单个句子的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']

标签: pythonexcelsplit

解决方案


使用 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()

推荐阅读