将Python文本文件字符串转换为电子表格中的列 [英] Python text file strings into columns in spreadsheet

查看:271
本文介绍了将Python文本文件字符串转换为电子表格中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的庞大新手,这可能真的很容易,但我根本无法理解.

Huge newbie to python and this is probably really easy, but I can't get my head around it at all.

我有一个文本文件,该文件的许多行都遵循这种格式

I have a text file with a number of rows following this format

 nothing doing    nothing[0]    doing[0] 
 hello world      hello[0]        world[2]

字符串之间只有空格,没有标记.

There are only spaces between the strings, no markers.

我想以以下格式将这些字符串提取到excel文件中-以便每个集合"字符串都位于单独的列中.

I'd like to extract these strings into excel file in the following format - so that each 'set' of strings are in a separate column.

           |        1      |       2        |       3
    ------------------------------------------------------
      1    | nothing doing |   nothing[0]   |  doing[0] 
    ------------------------------------------------------
      2    | hello world   |   hello[0]     |  world[2]

我一直在这里寻找答案,但是他们并不能完全解决这个问题.

I've been looking at answers on here but they don't quite full fill this question.

推荐答案

好的,这是您写入实际Excel文件的方式.请注意,我的拆分方法并不像其他方法那样复杂,因为这主要是关于写入Excel.您需要 python-excel 软件包才能做到这一点.

Alright, here's how you'd write to an actual Excel file. Note that my method of splitting isn't as complicated as others because this is mostly about writing to Excel. You'll need the python-excel package to do this.

>>> data = []
>>> with open("data.txt") as f:
...     for line in f:
...         data.append([word for word in line.split("  ") if word])
...
>>> print data
[['nothing doing', 'nothing[0]', 'doing[0]\n'], ['hello world', 'hello[0]', 'world[2]']]
>>>
>>> import xlwt
>>> wb = xlwt.Workbook()
>>> sheet = wb.add_sheet("New Sheet")
>>> for row_index in range(len(data)):
...     for col_index in range(len(data[row_index])):
...         sheet.write(row_index, col_index, data[row_index][col_index])
>>>
>>> wb.save("newSheet.xls")
>>>

这将生成一个工作簿,其中包含一个名为"New Sheet"的工作表,如下所示

This produces a workbook with one sheet called "New Sheet" that looks like this

希望这会有所帮助

这篇关于将Python文本文件字符串转换为电子表格中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆