文本文件中的出现次数[关闭]

问题描述 投票:-1回答:1
我有200个文本文件,希望计算每个文本文件中每个单词的出现次数,并每次都保存到不同的文本文件中

count = {} for w in open('Vimle_P_006_0_E1900.txt',errors='ignore',encoding='utf8').read().split(): if w in count: count[w] += 1 else: count[w] = 1 for word, times in count.items(): out_put = str(word) + " was found = " + str(times) + " times" + "\n" with open('Test.txt','a',encoding='utf8') as f: f.write(out_put) f.close()

python python-3.x file python-3.7
1个回答
0
投票
假设您有200个文本文件的列表list_of_files,您可以这样做:

def write_to_files(infile): count = {} for w in open(infile,errors='ignore',encoding='utf8').read().split(): #open the file if w in count: count[w] += 1 else: count[w] = 1 for word, times in count.items(): out_put = str(word) + " was found = " + str(times) + " times" + "\n" with open(infile+"_out.txt",'a',encoding='utf8') as f: #write to a different file each time f.write(out_put) for file in list_of_files: write_to_files(file) #iterate over the list of files and call the function for each file separately

© www.soinside.com 2019 - 2024. All rights reserved.