【问题标题】:Write dictionary of lists to xls in Python在 Python 中将列表字典写入 xls
【发布时间】:2013-08-08 10:57:45
【问题描述】:

使用 Python 1.5 个月。我将 Python 3.3.2 与 WinPython http://code.google.com/p/winpython/ 一起使用,并将 xlwt 从此处https://github.com/hansrwl/xlwt/tree/py3 移植到 Python 3 这是将值作为列表的 dict。它使用以下函数正确写入 xls 文件。

sampleData = {'Books': ['Book_A', 'Book_B', 'Book_C'],
              'Author': ['Author_A', 'Author_B', 'Author_C'],
              'Price': ['Price_A', 'Price_B', 'Price_C']}

功能:

def saveDataToNewFile(fileName, sheetName, data):
    # Creating new workbook
    wb = xlwt.Workbook()
    # Creating new worksheet with the name specified
    ws = wb.add_sheet(sheetName)
    # Use dictionary keys as first row values(e.g. headers)
    for colIdx, headerCaption in enumerate(data):
        ws.write(0, colIdx, headerCaption)
        # Use dict values as row values for corresponding columns
        for rowIdx, itemVal in enumerate(data[headerCaption]):
            ws.write(rowIdx + 1, colIdx, itemVal)
    wb.save(fileName)

saveDataToNewFile('sample.xls', 'FirstSaveToXlsSample', sampleData)

- 正确保存并使用 MS Excel 打开。

我有这个循环产生的相同数据结构:

soup3 = defaultdict(list)
def init_fields(links_first_lvl):
    for link in links_first_lvl[1:7]:
soup3['Дата'].append(BeautifulSoup(urllib.request.urlopen(link).read()).select('.author_data'))
            soup3['Адрес'].append(link)
        return soup3

这是结构,以列表为值的字典(我使用 pprint 在控制台美中打印)

PPRINT:
{'url': [  'http://www.ros.ru/article.php?chapter=1&id=20132503',
           'http://www.ros.ru/article.php?chapter=1&id=20132411'],
 'date': [[<div class="author_data"><b>Марта Моисеева
</b> № 30 (973) от 24.07.2013
<span class="rubr"> ВЛАСТЬ
</span></div>],
          [<div class="author_data"><b>Ольга Космынина
</b> № 29 (972) от 17.07.2013
<span class="rubr"> ВЛАСТЬ
</span></div>]]

saveDataToNewFile('sample2.xls', 'FirstSaveToXlsSample', soup3)

问题:如果我尝试保存到 xls 我得到一个错误:

.....

if isinstance(data, basestring):
NameError: global name 'basestring' is not defined

编辑:这是控制台 Pycharm 中的完整错误堆栈

Traceback (most recent call last):
  File "F:/Python/NLTK packages/parse_html_py3.3.2.py", line 91, in <module>
    saveDataToNewFile('sample2.xls', 'FirstSaveToXlsSample', soup3)
  File "F:/Python/NLTK packages/parse_html_py3.3.2.py", line 87, in saveDataToNewFile
    ws.write(rowIdx + 1, colIdx, itemVal)
  File "F:\WinPython-32bit-3.3.2.0\python-3.3.2\lib\site-packages\xlwt\Worksheet.py", line 1032, in write
    self.row(r).write(c, label, style)
  File "F:\WinPython-32bit-3.3.2.0\python-3.3.2\lib\site-packages\xlwt\Row.py", line 259, in write
    self.__rich_text_helper(col, label, style, style_index)
  File "F:\WinPython-32bit-3.3.2.0\python-3.3.2\lib\site-packages\xlwt\Row.py", line 276, in __rich_text_helper
    if isinstance(data, basestring):
NameError: global name 'basestring' is not defined

我不知道为什么,它应该可以工作,因为结构是一样的。

【问题讨论】:

  • 这个错误发生在哪里?它在 xls 库中吗?
  • 在上面的帖子中添加到编辑
  • 似乎您使用的只是python2的东西。 basestring 在 python3 中不存在。

标签: python dictionary xls xlwt


【解决方案1】:

您使用的库仅适用于 python 2.x。从here 下载最新的python 2.x 并重试。

【讨论】:

    【解决方案2】:

    LibreOffice 的开销大大降低。打开 LibreOffice 安装文件夹,并从那里的所有当前示例中搜索您的 UNO 引用。另存为 XLS。完成。

    【讨论】:

      【解决方案3】:

      正如 cmets 建议的那样,问题在于您使用的代码仍然是为 Python 2 编写的,但是,在按照 nosklo 的建议降级到 Python 2 之前,请确保您从 Python 3 分支安装了 xlwt /强>。克隆 xlwt 存储库后,您是否记得执行

      git checkout -b py3 origin/py3
      

      您执行安装之前?

      如果你记得并且仍然得到basestring错误,那么py3分支仍然不完整,你需要降级到Python 2才能运行master分支中的代码。

      【讨论】:

        【解决方案4】:

        您可以尝试将 'basestring' 更改为 'str'

        【讨论】:

          【解决方案5】:
          if isinstance(data, basestring):
              NameError: global name 'basestring' is not defined
          

          可能该对象没有这样的属性并且您的测试失败,因为它只是测试对象类型是否为实例,这意味着您的属性或对象已经存在。

          我建议您执行预先测试以验证属性或对象是否存在,例如 hasattr() 或者您是否考虑使用 self 您可以阅读 self.__dict__ 查找现有属性。

          【讨论】:

            猜你喜欢
            • 2016-03-01
            • 1970-01-01
            • 2018-07-18
            • 2016-07-11
            • 1970-01-01
            • 2012-11-04
            • 1970-01-01
            • 2021-03-22
            • 2014-06-17
            相关资源
            最近更新 更多