我正在尝试编写一个脚本来提取目录中许多文件的字数。我有它的工作相当接近我想要的,但有一个部分是让我放弃。迄今为止的准则是:
import glob
directory = "/Users/.../.../files/*"
output = "/Users/.../.../output.txt"
filepath = glob.glob(directory)
def wordCount(filepath):
for file in filepath:
name = file
fileO = open(file, 'r')
for line in fileO:
sentences = 0
sentences += line.count('.') + line.count('!') + line.count('?')
tempwords = line.split()
words = 0
words += len(tempwords)
outputO = open(output, "a")
outputO.write("Name: " + name + "\n" + "Words: " + str(words) + "\n")
wordCount(filepath)
这会将字数写入名为“的文件”输出.txt“并给出如下输出:
^{pr2}$这对目录中的每个文件都会重复。如您所见,它为每个文件提供了多个计数。文件的格式如下:
Address on Administration Goals Before a Joint Session of Congress
February 9, 1989
Mr. Speaker, Mr. President, and distinguished Members of the House and Senate...
所以,脚本似乎给了我文件中每个“部分”的计数,比如第一行的10个单词,第二行的0个单词,下一行的3个单词,下一行的0个单词,然后是文本正文的计数。在
我要找的是每个文件的一个计数。感谢任何帮助/指导。在
内部循环的最后两行打印出文件名和字数,应该是外循环的一部分,而不是内部循环的一部分,因为实际上,它们每行运行一次。在
你还需要重置每行的句子和单词数-这些应该在外循环中,在内环开始之前。在
以下是更改后代码的外观:
你的识别不对吗?我的意思是,最后一行每行调用一次,但你真的是说每个文件都调用一次,不是吗?在
(此外,尽量避免将“file”作为标识符-它是Python类型)
相关问题 更多 >
编程相关推荐