3

我有一个带有 ff: row/col 结构的 Excel 文件

ID   English   Spanish   French
 1   Hello     Hilo      Halu
 2   Hi        Hye       Ghi
 3   Bus       Buzz      Bas

我想读取 Excel 文件,提取行和列值,并基于英语、西班牙语和法语列创建 3 个新文件。

所以我会有类似的东西:

英文文件:

"1" = "Hello"
"2" = "Hi"
"3" = "Bus"

我一直在使用 xlrd。我可以打开、阅读和打印文件的内容。但是,这是我使用此命令得到的结果(Excel 文件已经打开):

for index in xrange(0,2):
    theWord = '\n' + str(sh.col_values(index, start_rowx=index, end_rowx=1)) + '=' + str(sh.col_values(index+1, start_rowx=index, end_rowx = 1))
    print theWord

输出:

[u'Parameter/Variable/Key/String']=[u'ENGLISH'] <-- is this a list?, didn't the str() use to strip it out?

你在那里做什么?如何删除方括号?

4

3 回答 3

4

u意味着它是一个 unicode 字符串,当您调用str(). 如果您将字符串写入文件,它将不存在。你得到的是列中的 1 行。这是因为您正在使用end_rowx=1它返回一个包含一个元素的列表。

尝试获取列值列表:

ids = sh.col_values(0, start_rowx=1)
english = sh.col_values(1, start_rowx=1)
spanish = sh.col_values(2, start_rowx=1)
french = sh.col_values(3, start_rowx=1)

然后您可以zip将它们放入元组列表中:

english_with_IDS = zip(ids, english)
spanish_with_IDS = zip(ids, spanish)
french_with_IDS = zip(ids, french)

形式为:

("1", "Hello"),("2", "Hi"), ("3", "Bus")

如果要打印对:

for id, word in english_with_IDS:
       print id + "=" + word

col_values返回列值列表,如果您想要单个值,您可以调用sh.cell_value(rowx, cellx).

于 2013-02-18T08:36:06.920 回答
3
import xlrd

sh = xlrd.open_workbook('input.xls').sheet_by_index(0)
english = open("english.txt", 'w')
spanish = open("spanish.txt", 'w')
french = open("french.txt", 'w')
try:
    for rownum in range(sh.nrows):
        english.write(str(rownum)+ " = " +str(sh.cell(rownum, 0).value)+"\n")
        spanish.write(str(rownum)+ " = " +str(sh.cell(rownum, 1).value)+"\n")
        french.write(str(rownum)+ " = " +str(sh.cell(rownum, 2).value)+"\n")
finally:
    english.close()
    spanish.close()
    french.close()
于 2013-02-18T09:22:33.120 回答
2

使用熊猫

In [1]: import pandas as pd

In [2]: df = pd.ExcelFile('test.xls').parse('Sheet1', index_col=0) # reads file

In [3]: df.index = df.index.map(int)

In [4]: for col in df.columns:
   ...:     column = df[col]
   ...:     column.to_csv(column.name, sep='=')  # writes each column to a file                                                    
   ...:                                          # with filename == column name

In [5]: !cat English  # English file content
1=Hello
2=Hi
3=Bus
于 2013-02-18T08:41:09.227 回答