私は記事が少ないフォルダがあり、tf-idf変換のリストを使用するために各記事のテキストを共通のリストにマップしたいと思います。たとえば、次のリストにフォルダからリストへの記事のマッピング
フォルダ= [1条、article2、article3]
リスト= [ '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
I私の記事でフォルダへのパスを設定すると、空のリストが表示されます。しかし、1つの記事に直接設定すると、その記事がリストに表示されます。どうすればそれらをすべて私のリストに写すことができますか? :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号は、実際には最初のものです新しく作成されたリストの1つ。
ご協力ありがとうございます。私はそれらをすべて試してみました。彼らのすべては、記事のいくつかを複製してもグロブのアプローチで、私の記事をシャッフルしました。私は理解していない、私は彼らが私のフォルダにあるように注文する記事が必要です。さらに、os.listdir(path)アプローチは、2番目の記事が存在しないが、それを自分のリストにマップするというエラーを報告しました。 Hm ...:S – guzdeh
os.listdirに固執しましょう。それを使用して質問を編集して最新のコードを表示し、これらのエラーと結果に関するすべての詳細を含めてください。 –
ねえ、あなたは何が問題なのか知っていますか? :) – guzdeh