将清单写入Excel [英] Write a list into Excel

查看:50
本文介绍了将清单写入Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一句话:现在换个完全不同的东西".我想标记它,标记它并将其存储到excel文件中以进行进一步处理.
< pre> sent =现在是完全不同的东西了"单词= nltk.word_tokenize(已发送)标签= nltk.pos_tag()打印标签</pre>

I have a sentence 'And now for something completely different'. I want to tokenize it, tag it and store it into a excel file for further processing.
<pre>sent = "And now for something completely different" words = nltk.word_tokenize(sent) tags = nltk.pos_tag() print tags</pre>

上面的结果是带有嵌套列表格式的带有标签的单词.

The result of above is the words with their tag in a nested list format.

[('And','CC'),('now','RB'),('for','IN'),('something','NN'),(完全","RB"),(不同","JJ")]

[('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN'), ('completely', 'RB'), ('different', 'JJ')]

我想将此结果列表存储到excel文件中,一列中包含单词,另一列中包含标签.

我尝试了以下代码来实现以上目标.

I want to store this result list into a excel file, with words in one column and tags to the other.

I tried the following code to achieve the above.

fd = open("output.txt",'w')
i=0
for words in tags:
    for word in words:
        i+=1
        fd.write(word)
        if i==1:
            fd.write('\t')
        fd.write('\n')
    i=0

上面的代码将把单词和标签完美地写到输出文件中.如果我使用shutil方法从文本文件复制到excel格式,它将完美执行.当我尝试读取转换后的问题时,问题就来了.我收到以下错误.

The above code will perfectly write the words and tag into the output file. If I use shutil method to copy from the text file to excel format, it will execute perfectly. The problem comes when I try to read the converted. I get the following error.

XLRDError:不支持的格式,或文件损坏:预期的BOF记录;基金会'And \ tCC \ n'

XLRDError: Unsupported format, or currupt file: Expected BOF record; founf 'And\tCC\n'

谁能告诉我如何将标记列表写入输出文件,以便上述错误可以解决?

Can anyone tell me how do I write the tagged list to the output file such that I the above error can be resolved?

推荐答案

Excel文件(xlsx)不仅仅是简单的平面文件,因此尝试将文本文件复制到xlsx无效.您可以将文件另存为csv,然后在Excel中打开.我认为pandas对于解析和写入数据文件确实很有用(显然,它对处理数据也很有用).

Excel files (xlsx) are not just simple flat files, so trying to copy a text file to xlsx will not work. You could save the file as csv and open it in Excel. I think pandas is really useful for parsing and writing data files (obviously it is also useful for processing data).

import pandas as pd
df = pd.DataFrame(tags)
df.to_excel('output.xlsx', header=False, index=False)

这篇关于将清单写入Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆