打开从 os.listdir() 找到的文件并对文件执行任务

CHb*_*ler 1 python directory file pipe python-2.7

所以我想打开一个目录中的每个文件(这个目录中有4个纯文本文档)。并执行诸如查找特定单词及其在每个文件中出现的次数之类的操作。

这是我使用的代码,但是我得到了没有这样的文件或目录的错误,但是我在打印路径时,它清楚地显示了每个文件的名称。

import re
import os

path = 'C:\\Python27\\projects\\Alabama\\New folder'

pattern = re.compile(r"\bmay not\b",re.IGNORECASE)
pattern1 = re.compile(r"\bshall\b",re.IGNORECASE)
pattern2 = re.compile(r"\bmust\b",re.IGNORECASE)
pattern3 = re.compile(r"\bprohibited\b",re.IGNORECASE)
pattern4 = re.compile(r"\brequired\b",re.IGNORECASE)

for filenames in os.listdir(path):
 with open(filenames) as myfile:
    total = 0
    total1 = 0
    total2 = 0
    total3 = 0
    total4 = 0
    for line in myfile:
        m = re.findall(pattern, line)
        m1 = re.findall(pattern1, line)
        m2 = re.findall(pattern2, line)
        m3 = re.findall(pattern3, line)
        m4 = re.findall(pattern4, line)
        total += len(m)
        total1 += len(m1)
        total2 += len(m2)
        total3 += len(m3)
        total4 += len(m4)
    print total, total1, total2, total3, total4
Run Code Online (Sandbox Code Playgroud)

我的问题是:如何执行上述任务,分别查找目录中每个文档的特定单词(“shall”“must”等)的单词出现次数?

Dee*_*ace 6

listdir仅返回文件名。您必须将路径附加回文件名才能打开它们。

for filenames in os.listdir(path):
    with open(os.path.join(path, filenames)) as myfile:
Run Code Online (Sandbox Code Playgroud)

至于计算单词数,您有多种选择,具体取决于您希望计算的精确程度以及您对“出现”的定义。例如,您可以将整个文件作为字符串读取,然后使用str.count方法仅计算特定单词的出现次数。

for filenames in os.listdir(path):
    with open(os.path.join(path, filenames)) as myfile:
        content = myfile.read().lower()  # to essentially ignore the case
        shall_count = content.count('shall')
Run Code Online (Sandbox Code Playgroud)