Python 1.5 个月。我正在将 Python 3.3.2 与 WinPython http://code.google.com/p/winpython/一起使用,并将 xlwt 从这里移植到 Python 3 https://github.com/hansrwl/xlwt/tree/py3 这是 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
我不知道为什么,它应该可以工作,因为结构是相同的。