0

到目前为止,我的代码是这样的:

from glob import glob
shakedir='D:\report\shakeall'
from shakedir import isfile
def countwords(fp):
   with open(fp) as fh:
       return len(fh.read().split())
print "There are" ,sum(map(countwords, filter(isfile, glob("*.txt") ) ) ), "words in the files."

问题是这段代码不起作用:)

我不习惯 Python 语法,所以我什么都试过了。

我想要的是,我希望这个脚本从特定目录导入文本文件。

不是来自os.path我的 .py 文件所在的 .

我想从中导入D:\report\shakeall,但我不能。而已。

感谢您的任何建议。

4

4 回答 4

1

您也可以glob为此目的单独使用函数:

from glob import glob

pattern = "D:\\report\\shakeall\\*.txt"
filelist = glob(pattern)

然后在该文件列表上做任何你想做的事情。您的方式现在应该可行:

def countwords(fp):
    with open(fp) as fh:
        return len(fh.read().split())

print "There are" ,sum(map(countwords, filelist))), "words in the files."
于 2012-08-08T12:53:57.957 回答
0

如果我正确理解您的问题,您需要的是:

shakedir = "d:\\report\\shakeall"
..
print "There are" ,sum(map(countwords, filter(isfile, glob(shakedir + "\\*.txt"))))), ".."
                                                           ^^^^^ It can take directories too..

该行:

from shakedir import isfile

对我没有任何意义。并为 isfile 提供一个实现,或者使用来自 os 模块的实现。

于 2012-08-08T12:51:28.597 回答
0

反斜杠表示字符串文字中的转义。尝试任一

"d:/report/shakeall"

或者

"d:\\report\\shakeall"

理想情况下:

os.path.join("d:", "report/", "shakeall")
于 2012-08-08T12:49:45.130 回答
0

您可以使用os.walk("pathname")获取某个目录中的文件列表。 http://docs.python.org/library/os#os.walk

于 2012-08-08T12:42:33.300 回答