代码之家  ›  专栏  ›  技术社区  ›  Henry

Python:遍历多个文本文件,提取目标字符串,并将其附加到列表中

  •  0
  • Henry  · 技术社区  · 9 年前

    (Python 3.6.3)

    这是我的代码:

    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
    

    我假设我试图提取的数据不是字符串形式,但不完全理解它的含义。我很欣赏任何指向正确方向的指针。非常感谢。

    1 回复  |  直到 9 年前
        1
  •  0
  •   Henry    9 年前

    在接受了@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