【发布时间】:2012-01-31 15:25:05
【问题描述】:
我是 python 新手,我需要编写一个脚本来计算目录中所有 txt 文件中的所有单词。这是我到目前为止所拥有的,其他方法仅在打开 txt 文件时有效,但是当我进入目录时它会失败。我知道我需要在某个地方追加,我尝试了几种不同的方法,但运气不佳。
*edit 我希望将结果集中在一起。到目前为止,它有 2 个单独的结果。我尝试制作一个新列表并将其附上计数器。但它坏了。再次感谢,这是一个很好的社区
import re
import os
import sys
import os.path
import fnmatch
import collections
def search( file ):
if os.path.isdir(path) == True:
for root, dirs, files in os.walk(path):
for file in files:
words = re.findall('\w+', open(file).read().lower())
ignore = ['the','a','if','in','it','of','or','on','and','to']
counter=collections.Counter(x for x in words if x not in ignore)
print(counter.most_common(10))
else:
words = re.findall('\w+', open(path).read().lower())
ignore = ['the','a','if','in','it','of','or','on','and','to']
counter=collections.Counter(x for x in words if x not in ignore)
print(counter.most_common(10))
path = input("Enter file and path, place ' before and after the file path: ")
search(path)
raw_input("Press enter to close: ")
【问题讨论】:
-
“失败”是什么意思?除此之外,我在任何地方都看不到
.txt限制。 -
if os.path.isdir(path) == True可以缩短为if os.path.isdir(path)
标签: python