【问题标题】:Getting rid of .DS_Store file while creating a corpus from scratch从头开始创建语料库时摆脱 .DS_Store 文件
【发布时间】:2021-04-08 22:37:49
【问题描述】:

我对 Python 非常陌生,我需要从头开始创建语料库。我的 .DS_Store 文件有问题。我尝试手动擦除它,使用终端擦除它或使用 Python 擦除它,但没有任何效果。当 .DS_Store 存在时,我无法进行 NLP 计算。这是我的代码:

import nltk
import random
nltk.download('cmudict')
nltk.download('wordnet')
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger')
nltk.download('punkt')
from nltk.corpus import cmudict
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import stopwords
import string
from nltk import word_tokenize
import os
from nltk.corpus.reader.plaintext import PlaintextCorpusReader

corpusdir = '/Users/username/nltk_data/corpusfilename'
corp = PlaintextCorpusReader(corpusdir, '.*')
corp.fileids() # gives me 6 fileids, 5 existing and one .DS_Store

corp.sents() # error: 'utf-8' codec can't decode byte 0xd5 in position 161: invalid 
continuation byte

我使用的是 Mac,建议使用 if 语句,这样语料库只能读取 .txt 而不能读取 .DS_Store。我不知道该怎么做。

【问题讨论】:

  • 这里的主要目标是将PlaintextCorpusReader 指向正确的文件,在这方面您应该接受@ygorg 给出的答案并重新表述您的问题及其标题以帮助未来的读者。谢谢!

标签: python nlp nltk corpus


【解决方案1】:

来自Wikipedia

在 Apple macOS 操作系统中,.DS_Store 是一个文件,用于存储其包含文件夹的自定义属性,例如图标的位置或背景图像的选择。

所以很可能总会有.DS_Store,在任何地方。

在这一行:corp = PlaintextCorpusReader(corpusdir, '.*') 你选择哪些文件将在语料库中。

第二个参数'.*' 是一个正则表达式,用于选择要使用的文件。根据the doc,这个参数可以是“A list or regexp specified the fileids in this corpus.”。

因此,在您的情况下,您可以将匹配所有内容的 '.*' 更改为 '.*\.txt' 以匹配任何字符和“。”和'txt'。或者,如果您知道需要的每个文件的名称,则可以使用文件名列表['file1.txt', 'file2.txt']

【讨论】:

    【解决方案2】:

    find . -name ".DS_Store" -delete

    上面的脚本可以从你的目录中删除文件。

    【讨论】:

    • 感谢您的回复。我将它复制到 Jupyter 笔记本并运行它,但它给了我一个语法错误(无效的语法)。我应该在终端还是 Python 中运行它?
    • 你应该在终端运行这个。
    猜你喜欢
    • 1970-01-01
    • 2019-07-17
    • 2016-09-22
    • 2016-03-17
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    相关资源
    最近更新 更多