【问题标题】:How to read multiple nltk corpus files and write in a single text file in python如何在python中读取多个nltk语料库文件并写入单个文本文件
【发布时间】:2017-02-10 01:45:35
【问题描述】:

我写了以下代码:

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

【问题讨论】:

    标签: python python-3.x nltk corpus


    【解决方案1】:

    如错误消息的最后一行所示,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", "overheard.txt", "pirates. txt", "singles.txt", "wine.txt"] with open("merge.txt", "w") as f: for file in files: f.write(nltk.corpus.webtext.raw(file) ) 我收到以下错误:7 with open("merge.txt", "w") as f: 8 for file in files: ----> 9 f.write(nltk.corpus.webtext .raw(file)) UnicodeEncodeError: 'charmap' codec can't encode character '\x99' in position 95156: character maps to
    • @Mitesh,你确定你使用的是 Python 3 吗?
    • @alexis 是 python 3.5
    • 告诉它你想对合并文件使用什么编码:open("merge.txt", "w", encoding="utf-8").
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2020-04-26
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多