【问题标题】:How to fix a FileNotFoundError while accessing files in a corpus如何在访问语料库中的文件时修复 FileNotFoundError
【发布时间】:2020-10-22 23:29:16
【问题描述】:

我正在尝试编写代码来访问名为 Mini-CORE 的语料库中的文件。我打印listdir 并从中提取流派代码没有问题。但是,当我尝试访问文件本身以提取文本时,它给了我FileNotFoundError: [Errno 2] No such file or directory: '1+IN+EN+IN-IN-IN-IN+EN-EN-EN-EN+WIKI+9990014.txt',这是文件夹中的第一个文件名。所以我很困惑,如果它声称它不存在,为什么它会告诉我文件名?我是不是在某处犯了语法错误?

import os
import re
import spacy
from spacy import displacy
from collections import Counter

nlp = spacy.load('en')

entries = os.listdir('Mini-CORE')
entry_list = []

# this returns the genre codes for each file
def genre_code(filename):
    for entry in entries:
        regex1 = r'((?<=1\+)\w*)'  # This captures the genre code
        genre = re.findall(regex1, entry)
        entry_list.append(genre)
genre_code(entries)
print(entry_list)


# FileNotFoundError???
# This captures the text after after the <h> or <p> tags
def relevant_text(filename):
        for filename in entries:
            with open(filename) as current_file:
                text = current_file.read()
                regex2 = r'((?<=<h>|<p>).*)'
                text2 = re.findall(regex2, text)
                print(text2)

print(relevant_text(entries))

【问题讨论】:

  • listdir 结果不包含文件的路径。您可能希望将os.path.join('Mini-CORE', filename) 添加到放入entries 的每个名称中。 relevant_text() 似乎有问题。你传入一个filename,但立即用entries 的文件名覆盖它。这使得在不传播假定的错误的情况下很难写出答案。

标签: python corpus file-not-found


【解决方案1】:

os.listdir 返回不带路径的文件名。打开文件时需要文件的父目录。 pathlib 是一个面向对象的路径库,可以更轻松地传递路径,而无需担心目录和路径名。

使用Path.glob 列出目录,返回的路径将包含文件名及其路径供您的程序使用。通过一些清理,您的代码可能是

from pathlib import Path
import re
import spacy
from spacy import displacy
from collections import Counter

nlp = spacy.load('en')

entries = Path('Mini-CORE').glob("*")

# this returns the genre codes for each file
def genre_code(entries):
    entry_list = []
    for entry in entries:
        regex1 = r'((?<=1\+)\w*)'  # This captures the genre code
        genre = re.findall(regex1, entry.name)
        entry_list.append(genre)
    return entry_list
    
entry_list = genre_code(entries)
print(entry_list)

# This captures the text after after the <h> or <p> tags
def relevant_text(entries):
        for filename in entries:
            with open(filename) as current_file:
                text = current_file.read()
                regex2 = r'((?<=<h>|<p>).*)'
                text2 = re.findall(regex2, text)
                print(text2)

print(relevant_text(entries))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 2019-09-15
    • 2019-02-27
    相关资源
    最近更新 更多