2017-08-03 11 views
0

(Pythonの3.6.3)をリストするためにそれらを追加しパイソン:複数のテキストファイルをループし、抽出対象の文字列、および

私は長いテキスト文字列を含む複数のテキストファイルからIPアドレスと日付を抽出する必要があります。その後、これらのデータをPythonリストに追加したいと思います。これらのテキストファイルもサブディレクトリに置かれていますので、os.path.join(subdir、file)を使用してこれらのテキストファイルをキャプチャするようにしました。

ここに私のコードです:

ip_address = [] 
dates = [] 

for subdir, dirs, files in os.walk(rootdir): 
    for file in files: 
     if file.endswith('.txt'): 
      text_data = open(os.path.join(subdir, file)) 
      ip_address.append(re.findall(r'[0-9]+(?:\.[0-9]+){3}', text_data)) 
      dates.append(re.findall(r'[0-9]+(?:\/[0-9]+){2}', text_data)) 
     else: 
      pass 

しかし、私は次のエラーを取得する:

TypeError         Traceback (most recent call last) 
<ipython-input-28-de806e6c6270> in <module>() 
     6   if file.endswith('.txt'): 
     7    text_data = open(os.path.join(subdir, file)) 
----> 8    ip_address.append(re.findall(r'[0-9]+(?:\.[0-9]+){3}', text_data)) 
     9    dates.append(re.findall(r'[0-9]+(?:\/[0-9]+){2}', text_data)) 
    10   else: 

C:\Users\591159\AppData\Local\Continuum\Anaconda3\lib\re.py in findall(pattern, string, flags) 
    220 
    221  Empty matches are included in the result.""" 
--> 222  return _compile(pattern, flags).findall(string) 
    223 
    224 def finditer(pattern, string, flags=0): 

TypeError: expected string or bytes-like object 

私は抽出しようとしていたデータが文字列の形式でないと仮定したが、完全にありませんそれが何を意味するのかを理解する。私は正しい方向へのポインタを感謝します。ありがとうございました!

+2

は、あなたがに '読む()'データをもしかして - 例えば'text_data.read()'現在、 'text_data'は文字列ではなく文字列の反復子です。 – AChampion

+0

はい、私は文字列としてデータを読むことを意味しました。私のコードをどのように置き換えるべきですか?前もって感謝します。 – comproch

答えて

0

@AChampionからの提案を取った後、私は次のように私のコードを修正し、それが意図したとおりに動作します:

ip_address = [] 
dates = [] 

for subdir, dirs, files in os.walk(rootdir): 
    for file in files: 
     if file.endswith('.txt'): 
      with open(os.path.join(subdir, file), 'r', encoding='utf8') as text_file: 
       text_data = text_file.read().replace('\n', '') 
      ip_address.append(re.findall(r'[0-9]+(?:\.[0-9]+){3}', text_data)) 
      dates.append(re.findall(r'[0-9]+(?:\/[0-9]+){2}', text_data)) 
     else: 
      pass 
関連する問題