2016-12-20 4 views
1

私はsaprqlクエリを使ってwikipediaからダウンロードした1000個のテキストファイルをオープンして処理しようとしています。私は、次のコードを使用します。Pythonがディレクトリを通り抜けてtxtファイルを開く

list_words=[] 
for roots, dirs, files in os.walk(path): 
    for file in files: 
     if file.endswith(".txt"): 
      with open(file, 'r') as f: 
       content= f.read() 

       #remove the punct 
       table=string.maketrans(string.punctuation,' '*len(string.punctuation)) 
       s= content.translate(table) 


       #remove the stopwords 
       text= ' '.join([word for word in s.split() if word not in stopwords]) 
       alfa= " ".join(text.split()) 

       #remove the verbs 
       for word, pos in tag(alfa): # trovo tutti i verbi. 
        if pos != "VB": 
         lower= word.lower() 
         lower_2= unicode(lower, 'utf-8', errors='ignore') 
         list_words.append(lower_2) 

       #remove numbers 
       testo_2 = [item for item in list_words if not item.isdigit()] 

print set(list_words)   

問題は、スクリプトは、いくつかのテキストファイルを開いて、他人のためにそれは私にエラーを与えるということです。誰もが知ってい

を:「blablabla.txtないようなファイルやディレクトリを」なぜそれが起こり、どのように私はそれに対処することができますか?

ありがとうございます!

absolute_filename = os.path.join(roots, file) 
with open(absolute_filename, 'r') as f: 
    .... rest of code 

(それはroot代わりのroots名前を付ける必要があります):

+1

ファイルパスは、dirpathに関連するファイルの名前を示します。ファイルが作業ディレクトリにない場合、ファイルは見つかりません。 – Natecat

答えて

2

fileは、あなたがこのような絶対ファイル名を取得するには、ルートやファイルをCONCATする必要があり、相対的です。

+0

ありがとうアンソニー! – CosimoCD

+0

ちょっとアンソニー!私はあなたの手順に従っているが、私はそれが私に同じ問題を与えることを発見した: – CosimoCD

+0

ちょっとアンソニー!私はあなたの手順に従っているが、それは私に同じ問題を与える... IOError:[Errno 2]そのようなファイルやディレクトリはありません: 'C:\\ Users \\ Cosimo \\ Desktop \\ Tirocinio \\ progetto_arianna \\ Sintesi H2O_txt \ \ sintesi_txt \\ 1000testi \\ Andrej Aleksandrovic Mironov.txt – CosimoCD

関連する問題