【问题标题】:Writing a python script to scrape excel data and write to a CSV, how do I get the proper output?编写 python 脚本来抓取 excel 数据并写入 CSV,如何获得正确的输出?
【发布时间】:2018-12-25 17:37:47
【问题描述】:

我有一个 Excel 文档,其中包含名为“foo”的行和名为“bar”的列。 Foo 和 bar 有时与“x”相关联。

FooBar Tracker Excel Doc

我编写了一些 Python 代码,用于在文档中搜索“x”,然后列出相关的 foo 和 bar 值。当我只打印输出时,所有值都会打印到控制台。当我尝试将输出存储为变量并打印变量时,我只得到最终有效的 foo 和 bar 组合。

import xlrd
import csv

###Grab the data 
def get_row_values(workSheet, row):
    to_return = []
    num_cells = myWorksheet.ncols - 1
    curr_cell = -1
    while curr_cell < num_cells:
        curr_cell += 1
        cell_value = myWorksheet.cell_value(row, curr_cell)
        to_return.append(cell_value)
    return to_return

file_path = 'map_test.xlsx'

myWorkbook = xlrd.open_workbook(file_path)
myWorksheet = myWorkbook.sheet_by_name('Sheet1')
num_rows = myWorksheet.nrows - 1
curr_row = 0
column_names = get_row_values(myWorksheet, curr_row)
print len(column_names)
while curr_row < num_rows:
        curr_row += 1 
        row = myWorksheet.row(curr_row)
        this_row = get_row_values(myWorksheet, curr_row)
        x = 0
        while x <len(this_row):
            if this_row[x] == 'x':
                    #print this_row[0], column_names[x]  
### print this_row[0], column_names[x] works 
### when I un-comment it, and prints foo and bar associated in the 
### proper order
                    output = "[%s %s]" % (this_row[0], column_names[x]) 
            x += 1

print output 
###Using the output variable just outputs the last valid foo/bar 
###combination 

这是为什么?我如何解决它?

其次,当我尝试将数据写入 .csv 文件时,损坏的输出会添加到 .csv 中,每个单元格中都有一个字符。我需要能够让每个唯一值进入它自己的单元格,并控制它们进入哪些单元格。到目前为止,这是我所拥有的:

myData = [["number", "name", "version", "bar" "foo"]]

myFile = open('test123.csv', 'w')
with myFile:
        writer = csv.writer(myFile)
        writer.writerows(myData)
        writer.writerows(output) ###This just outputs the last valid foo 
###and bar combination
print ("CSV Written")

输出最终看起来像这样: Results I'm getting

但我希望它看起来像这样: Results I want

【问题讨论】:

    标签: python excel csv parsing


    【解决方案1】:

    您的output 变量(您的累加器)不会不断地添加值,而是在每次循环运行时覆盖行、列值。您的 print 语句有效,因为它正在为每个循环运行打印,这就是您所看到的。

    要解决此问题,请将输出变量设置为 while 循环之外的空列表:

    output = []
    

    然后改变这一行:

    output = "[%s %s]" % (this_row[0], column_names[x]) 
    

    到这里:

    output.append([this_row[0], column_names[x]]) 
    

    您遇到的另一个问题是您的输出结果很有趣。这是因为这一行:

    output = "[%s %s]" % (this_row[0], column_names[x]) 
    

    您要求 python 将this_row 渲染为字符串,然后在[0] 位置为您提供字符,这可能只是“f”。对代码的上述更改也解决了这个问题。

    附带说明,使用for 循环而不是while 循环会被认为是更好的形式。例如

    for row in range(0,num_rows) :
    

    【讨论】:

    • 事实证明,我只需将打印输出命令放入循环中即可解决我的第一个问题。我将检查这是否解决了我的第二个问题并进行更新。谢谢!
    • 明白。我抽出时间来写这个正确的答案。请照此授予。
    • 成功了,现在如何将 foo 和 bar 的输出转换到不同的列?
    • csvwriter 没有明确地“寻址”列,所以如果您需要重新整理,您需要在列表中添加空格。我假设您还需要切换 bar 和 foos 的顺序。使用像这样的列表理解来自动添加空格并切换顺序。假设这是你所拥有的:output_sample = [["foo1", "bar2"], ["foo1", "bar3"], ["foo2", "bar1"]] 这样做... rearranged_output = [["","","", foobars[1], foobars[0]] for foobars in output_sample] 要得到这个:[['', '', '', 'bar2', 'foo1'], ['','','','bar3','foo1'],...
    • 另外,将您的open 行更改为此以处理额外的空格:myFile = open('test.csv', 'w', newline = "")
    猜你喜欢
    • 2019-08-16
    • 2017-12-18
    • 2017-02-10
    • 1970-01-01
    • 2015-06-19
    • 2019-11-12
    • 2019-03-06
    • 1970-01-01
    • 2019-03-12
    相关资源
    最近更新 更多