Occurrences( inputFileNames, words, outputFileName )
对于列表inputFileNames
中的每个文件,输出到
名为outputFileName
的文件是输入的名称
文件,对于列表中的每个单词words
单个单词出现的次数;如果有任何输入
无法读取文件,请发出适当的错误消息
跳过那个文件。为了增加乐趣,不使用
.count()
内置函数
Occurrences( ["sample1.txt","sample2.txt","sample3.txt"],
["why","you","fate","among"], "out.txt")
out.txt
然后包含:
File Name: why you fate among
sample1.txt 3 0 0 0
sample2.txt 2 2 1 1
sample3.txt 0 3 0 0
到目前为止我得到的是
def Occurrences(inputFileNames,words,outputFileName):
output = open(outputFileName,"a")
try:
for file in inputFileNames:
opned = open(file,"r")
print(opned)
counters = [0 for file in range (len(words))]
index = 0
for i in words:
for line in opned:
if i in line:
print("WORD",i,"LINE",line)
counters[index] += 1
index +=1
print(counters)
except IOError:
file.close()
print("*** Occurrences: File handle Error")
我也绝对推荐使用计数法。从您的示例中,我看不出您在哪里尝试将结果写入输出文件,因此我将解释一个可能的实现
然后,occ.txt包含:
要在不使用count方法的情况下实现这一点,一种可能的方法是逐元素迭代contentlist元素,并在单词与元素匹配时增加计数
相关问题 更多 >
编程相关推荐