【发布时间】: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