【问题标题】:Mapping articles from folder into a list将文件夹中的文章映射到列表中
【发布时间】:2016-05-20 15:52:39
【问题描述】:

我有一个包含几篇文章的文件夹,我想将每篇文章的文本映射到一个通用列表中,以便将该列表用于 tf-idf 转换。例如:

文件夹 = [文章 1、文章 2、文章 3]

进入列表

list = ['text_of_article1', 'text_of_article2', 'text_of_article3']

def multiple_file(arg):     #arg is path to the folder with multiple files
    '''Function opens multiple files in a folder and maps each of them to a list
    as a string'''
    import glob, sys, errno
    path = arg
    files = glob.glob(path)
    list = []               #list where file string would be appended
    for item in files:    
        try:
            with open(item) as f: # No need to specify 'r': this is the default.
                list.append(f.read())
        except IOError as exc:
            if exc.errno != errno.EISDIR: # Do not fail if a directory is found, just ignore it.
                raise # Propagate other kinds of IOError.
    return list

当我为我的文章设置文件夹的路径时,我得到一个空列表。但是,当我直接将其设置为一篇文章时,该文章会出现在列表中。我怎样才能将它们全部映射到我的列表中。 :S

这是代码,不知道是不是你的想法:

def multiple_files(arg):     #arg is path to the folder with multiple files
    '''Function opens multiple files in a folder and maps each of them to a list
    as a string'''
    import glob, sys, errno, os
    path = arg
    files = os.listdir(path)
    list = []               #list where file string would be appended
    for item in files:    
        try:
            with open(item) as f: # No need to specify 'r': this is the default.
                list.append(f.read())
        except IOError as exc:
            if exc.errno != errno.EISDIR: # Do not fail if a directory is found, just ignore it.
                raise # Propagate other kinds of IOError.
    return list

这是错误:

Traceback (most recent call last):

  File "<ipython-input-7-13e1457699ff>", line 1, in <module>
    x = multiple_files(path)

  File "<ipython-input-5-6a8fab5c295f>", line 10, in multiple_files
    with open(item) as f: # No need to specify 'r': this is the default.

IOError: [Errno 2] No such file or directory: 'u02.txt'

第2条实际上是新创建的列表中的第一个。

【问题讨论】:

    标签: python string list function


    【解决方案1】:

    假设path == "/home/docs/guzdeh"。如果你只说glob.glob(path),你只会得到[path],因为没有其他匹配模式。您希望glob.glob(path + "/*") 获取该目录中的所有内容,或者glob.glob(path + "/*.txt") 获取所有txt 文件。

    您也可以使用import os; os.listdir(path),我认为这更有意义。

    更新:

    关于新代码,问题在于os.listdir 只返回相对于所列目录的路径。因此,您需要将两者结合起来让 python 知道您在说什么。添加:

    item = os.path.join(path, item)
    

    在尝试open(item) 之前。您可能还想更好地命名变量。

    【讨论】:

    • 感谢您的帮助。我把它们都试过了,它们都洗牌了我的文章,用全局方法甚至复制了一些文章。我不明白,我需要像在我的文件夹中一样订购文章。此外,os.listdir(path) 方法还报告了第二篇文章不存在但随后将其映射到我的列表中的错误。嗯... :S
    • 让我们坚持使用 os.listdir。使用它,编辑您的问题以显示最新代码,并包含有关这些错误和结果的所有详细信息。
    • 嘿,你知道可能是什么问题吗? :)
    • @guzdeh 嗨,对不起,不知道你已经编辑了。更新了我的答案。
    猜你喜欢
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2011-06-13
    • 1970-01-01
    • 2015-08-06
    • 2012-06-11
    相关资源
    最近更新 更多