【问题标题】:no such file or directory error(python)没有这样的文件或目录错误(python)
【发布时间】:2016-08-05 22:36:31
【问题描述】:

我有 3989 .txt 文件的文件。我使用 nltk 读取 txt 文件的 id 并将所有 id 放入文件中,现在我想读取每个 txt 文件并有两个输出,一个带有文本的语料库所有 txt 文件,其次是每个 txt 文件作为行的数组。但我什至无法读取文件,我有这个错误FileNotFoundError: [Errno 2] No such file or directory:。我怎样才能修复它并有我的两个输出?任何帮助表示赞赏! 这是我的代码:

from nltk.corpus import BracketParseCorpusReader

corpus_root = '/Users/sima/Downloads/Selected 20-newsgroupto work on/kole databaseha'
wordlists = PlaintextCorpusReader(corpus_root, '.*') 
files = wordlists.fileids()

for file in files:
    f = open(file,'r')
    lines = f.read()
    print(lines)

【问题讨论】:

    标签: file python-3.x nltk text-mining path-finding


    【解决方案1】:

    您需要 join basenameroot 目录,除非您的 cwd 是文件所在的位置,而您的错误是它们不是:

    from nltk.corpus import BracketParseCorpusReader
    from os.path import join
    
    corpus_root = '/Users/sima/Downloads/Selected 20-newsgroupto work on/kole databaseha'
    wordlists = PlaintextCorpusReader(corpus_root, '.*')
    files = wordlists.fileids()
    
    for file in files:
        with  open(join(corpus_root, file)) as f:
            lines = f.read()
            print(lines)
    

    【讨论】:

    • 我运行代码,这次不同的错误:Traceback(最近一次调用最后一次):文件“”,第 3 行,在 文件“/Users/sima/anaconda3/lib /python3.5/codecs.py",第 321 行,在 decode (result,consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf7 in position 557 : 无效的起始字节
    • 这与你原来的错误无关,是因为编码问题,尝试在open call中设置encoding="latin-1"
    • 我将其更改为 :with open(join(corpus_root, file), encoding = 'latin-1') as f: 并且可以正常工作。谢谢,
    猜你喜欢
    • 2015-07-12
    • 2022-10-21
    • 2021-10-31
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 2010-12-18
    • 2018-10-05
    • 1970-01-01
    相关资源
    最近更新 更多