![](/img/trans.png)
[英]Python: Counting words from a directory of txt files and writing word counts to a separate txt file
[英]counting appearances of a specific word in a .txt file in a directory
我正在嘗試編寫一個 function 來計算給定目錄中每個文件中特定單詞的出現次數。 希望在 python 中執行此操作。 我有些不知所措。
在文件.py
import os
files_and_directories = os.listdir("./files/")
prefix = './files/'
iterator = 0
for file in files_and_directories:
with open(f'{prefix}/{file}', 'r') as f:
for line in f:
for word in line.split():
if word == "Line":
print(word)
iterator += 1
print(iterator)
Of course, change the 'if word == "Line"' you whatever you want.
這種方法返回一個字典,其中包含path
指定的文件夾中每個文本文件的條目,其中鍵是文件名,值是字典,單詞作為鍵,計數作為值。
import os
from collections import Counter
def fun(path):
res = {}
for filename in os.listdir(path):
if filename.endswith('.txt'):
filepath = os.path.join(path, filename)
with open(filepath, 'r') as f:
words = f.read().split()
res[filename] = dict(Counter(words))
return res
您可以使用glob和下面的代碼創建一個包含文件名作為鍵和單詞出現計數的字典:
from glob import glob
word = 'apple'
result = {}
for filename in glob('./*.txt'):
with open(filename, 'r') as f:
result[filename] = len([w for w in f.read().replace('\n', ' ').split(' ') if w == word])
根據需要更改 word 變量的值
因此,如果當前文件夾中有兩個 txt 文件的內容:
文件1.txt
apple fruit apple
和
文件2.txt
apple fruit orange
結果字典將是:
{'./file2.txt': 1, './file1.txt': 2}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.