1.5個月的Python。我使用Python 3.3.2與WinPython http://code.google.com/p/winpython/和端口xlwt到Python 3從這裏https://github.com/hansrwl/xlwt/tree/py3 這是與列表值的字典。它使用以下函數正確寫入xls文件。用Python編寫列表的詞典到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
這裏是結構,字典,列表作爲值(I使用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庫中嗎? – Nadh
添加到上面編輯 –
似乎你使用的東西只是python2。 python3中不存在'basestring'。 – Bakuriu