gpt4 book ai didi

python - 使用 Python 从 Excel 中提取列

转载 作者:太空宇宙 更新时间:2023-11-03 12:49:35 25 4
gpt4 key购买 nike

我有一个包含 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?

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

最佳答案

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)

然后您可以将它们压缩到元组列表中:

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)

关于python - 使用 Python 从 Excel 中提取列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14931906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com