如何在python中读取多个nltk语料库文件并写入单个文本文件

如何在python中读取多个nltk语料库文件并写入单个文本文件,python,python-3.x,nltk,corpus,Python,Python 3.x,Nltk,Corpus,我编写了以下代码: import nltk 然后 我尝试在单个文件中写入内容的部分 filenames = [file1, file2, file3] with open('result.txt', 'w') as outfile: #want to store the contents of 3 files in result.txt for fname in filenames: with open(fname) as infile: for

我编写了以下代码:

import nltk
然后

我尝试在单个文件中写入内容的部分

filenames = [file1, file2, file3]
with open('result.txt', 'w') as outfile: #want to store the contents of 3 files in result.txt
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)
对此,我得到以下错误

TypeError                                 Traceback (most recent call last)
<ipython-input-9-917545c3c1ce> in <module>()
      2 with open('result.txt', 'w') as outfile:
      3     for fname in filenames:
----> 4         with open(fname) as infile:
      5             for line in infile:
      6                 outfile.write(line)

TypeError: invalid file: ['[', 'The', 'Tragedie', 'of', 'Julius', 'Caesar', ...]
TypeError回溯(最近一次调用)
在()
2以open('result.txt','w')作为输出文件:
3对于文件名中的fname:
---->4以开放(fname)作为填充:
5对于填充中的线:
6输出文件写入(行)
TypeError:无效文件:['[','The','Tragedie','of','Julius','Caesar',…]

如错误消息的最后一行所示,
file1
等不是文件名,而是单词列表。您不必使用words函数,只需将文件组合成如下所示:

filenames = [
    "shakespeare-caesar.txt",
    "shakespeare-hamlet.txt",
    "shakespeare-macbeth.txt"
]
with open("result.txt", "w") as f:
    for filename in filenames:
        f.write(nltk.corpus.gutenberg.raw(filename))

你知道为什么它不能在下面的代码中工作吗:files=[“firefox.txt”、“grail.txt”、“overread.txt”、“pirates.txt”、“singles.txt”、“wine.txt”]和open(“merge.txt”、“w”)作为f:for files中的文件:f.write(nltk.corpus.webtext.raw(file)),我得到以下错误:open(“merge.txt”、“w”)为7如f:8对于文件中的文件:-->9 f.write(nltk.corpus.webtext.raw(file))UnicodeEncodeError:“charmap”编解码器无法对95156位置的字符“\x99”进行编码:字符映射到@Mitesh,您确定使用的是Python 3吗?@alexis yes Python 3.5告诉它要对合并文件使用什么编码:
open(“merge.txt”,“w”,encoding=“utf-8”)
filenames = [
    "shakespeare-caesar.txt",
    "shakespeare-hamlet.txt",
    "shakespeare-macbeth.txt"
]
with open("result.txt", "w") as f:
    for filename in filenames:
        f.write(nltk.corpus.gutenberg.raw(filename))