在spreash中将Python文本文件字符串放入列中

2024-05-29 10:01:49 发布

您现在位置:Python中文网/ 问答频道 /正文

Python新手,这可能是真的很容易,但我无法得到我的头周围的一切。

我有一个文本文件,其中有许多行遵循此格式

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

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

我想以以下格式将这些字符串提取到excel文件中,以便每个“字符串集”都位于单独的列中。

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

我一直在这里寻找答案,但还没有完全回答这个问题。


Tags: 文件字符串答案标记helloworld格式excel
3条回答

有时,大多数使用Excel的人会对Excel如何显示其工作表和文件中的csv表示之间的差异感到困惑。在这里,尽管“马蒂诺”给了你你想要的东西,但我认为你真正想要的是:

import re, csv

with open("infile.txt") as fp_in, open("outfile.csv", "wb") as fp_out:
    writer = csv.writer(fp_out)
    for line in fp_in:
        row = re.split("\s\s+", line.strip())
        writer.writerow(row)

会变的

$ cat infile.txt 
nothing doing    nothing[0]    doing[0] 
hello world      hello[0]        world[2]

进入

$ cat outfile.csv 
nothing doing,nothing[0],doing[0]
hello world,hello[0],world[2]

可以使用numpy读取txt文件,使用csv将其作为csv文件写入。csv包以及其他包允许您选择首选项的分隔符。

import numpy
import csv

data = numpy.loadtxt('txtfile.txt', dtype=str)

with open('csvfile.csv', 'w') as fobj:
    csvwriter = csv.writer(fobj, delimiter=',')
    for row in data:
        csvwriter.writerow(row)

好的,下面是如何编写一个实际的Excel文件。请注意,我的拆分方法没有其他方法复杂,因为这主要是为了编写Excel。您需要python-excel包来完成此操作。

>>> 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")
>>>

这将生成一个工作簿,其中一个工作表名为“新工作表”,如下所示

Sample output

希望这有帮助

相关问题 更多 >

    热门问题