2017-12-22 4 views
1

を発見されたにもかかわらず、エラーが見つかりませんファイルは、ファイルには、次のコードビット使用

Traceback (most recent call last): File "text_statistics.py", line 28, in corpus_reading_pos(corpus_name, option) File "text_statistics.py", line 13, in corpus_reading_pos f= open(file) FileNotFoundError: [Errno 2] No such file or directory: 'abc_0001.v4_gold_conll'

は、あなたが見ることができるように、ファイルがでした実際には、しかし、私はファイルを開くしようとすると、それは...それを見つけることができません?

編集: この更新されたコードを使用すると、7つのファイルを読み込んだ後に停止しますが、172のファイルがあります。

def corpus_reading_token_count(corpus_name, option="token"): 
    for root, dirs, files in os.walk(corpus_name): 
     tokens = [] 
     file_count = 0 
     for file in files: 
      if file.endswith(".v4_gold_conll"): 
       with open((os.path.join(root, file))) as f: 
        tokens += [line.split()[3] for line in f if line.strip() and not line.startswith("#")] 
        file_count += 1 
    print(tokens) 
    print("File count:", file_count) 
+4

このファイルは 'corpus_name'にありますが、現在の作業ディレクトリで開きます。 –

+0

私のコーパスには何百ものファイルが含まれているので、 ".v4_gold_conll"で終わるファイルだけにアクセスして情報を抽出する必要があります。どのように私はそれについて行くだろうか分からない... – socrlax24

答えて

2

fileあなたのコードでrootあるディレクトリのない単なるファイルです。

f = open(os.path.join(root, file))) 

また、あなたがより良いファイルを開くためにwithを使用する必要があり、および組み込みタイプのシャドウイング、変数名としてfileを使用しない:これを試してみてください。また、あなたのコメントから判断すると、あなたはおそらく(代わりに=+=を使用)トークンのリストを拡張する必要があります。

tokens = [] 
for root, dirs, files in os.walk(corpus_name): 
    for filename in files: 
     if filename.endswith(".v4_gold_conll"): 
      with open(os.path.join(root, filename))) as f: 
       tokens += [line.split()[3] for line in f if line.strip() and not line.startswith("#")] 
print(tokens) 
+0

ありがとう、これは働いたが、この部分を置き換えた後、それは1つのファイルからトークンを抽出し、すべてのファイルを抽出していない? – socrlax24

+0

@ socrlax24私の編集を参照してください。 –

+0

今は、7つのファイルを開いただけで停止する問題があります。フォルダとサブフォルダには172個のファイルが必要です。 – socrlax24

0

あなたはファイル名でrootに参加する必要があります。

for root, dirs, files in os.walk(corpus_name): 
    for file in files: 
     if file.endswith(".v4_gold_conll"): 
      with open(os.path.join(root, file)) as f: 
      tokens = [ 
       line.split()[3] 
       for line in f 
       if line.strip() and not line.startswith("#") 
      ] 
      print(tokens) 
関連する問題