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

标签 python python-3.x nltk corpus

我编写了以下代码:

import nltk

然后

file1 = nltk.corpus.gutenberg.words('shakespeare-caesar.txt')
file2 = nltk.corpus.gutenberg.words('shakespeare-hamlet.txt')
file3 = nltk.corpus.gutenberg.words('shakespeare-macbeth.txt')

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

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', ...]

最佳答案

如错误消息中的最后一行所示,file1 et al.不是文件名,而是单词列表。您可以将这些文件合并为一个文件,而不是使用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))

关于python - 如何在Python中读取多个nltk语料库文件并写入单个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42150166/

相关文章:

python - Choropleth map 不为国家着色?

python - Pandas dataframe.query 到 SQL 'LIKE' 而不使用引擎 ='python'

python - 我无法运行由 cx_Freeze 构建的电子邮件程序

python - 使用 NLTK 创建新语料库

python - 用于民族的 Python 中的智能词干提取/词形还原

python - 在 HTML 文件中查找字符串?

python - 如何将新的键值对添加到字典中,其中值是数组的数组

python - 将多个句子标记为 python pandas 中的行

python - 枚举在 Python 2.7 中不可迭代

python - pip(或 setuptools、distribute 等)可以列出每个已安装软件包使用的许可证吗?