Python 如何在目录中的所有文件上运行脚本?
我有一个脚本,可以进行一些基本的文本清理和标记化,然后计算和排序词频。我能够让脚本在单个文件上工作,但我需要帮助在整个目录上实现它。简而言之,我想用这段代码计算整个目录中的全局单词频率(而不是为每个文件返回单个值) 这是我的密码:Python 如何在目录中的所有文件上运行脚本?,python,directory,Python,Directory,我有一个脚本,可以进行一些基本的文本清理和标记化,然后计算和排序词频。我能够让脚本在单个文件上工作,但我需要帮助在整个目录上实现它。简而言之,我想用这段代码计算整个目录中的全局单词频率(而不是为每个文件返回单个值) 这是我的密码: import re import string from collections import Counter file = open("german/test/polarity/positive/0.txt", mode="r", encoding="utf-8"
import re
import string
from collections import Counter
file = open("german/test/polarity/positive/0.txt", mode="r", encoding="utf-8")
read_file = file.read()
#remove punctuation
translation = str.maketrans("","", string.punctuation)
stripped_file = read_file.translate(translation)
##lowercase
file_clean = stripped_file.lower()
##tokenize
file_tokens = file_clean.split()
##word count and sort
def word_count(file_tokens):
for word in file_tokens:
count = Counter(file_tokens)
return count
print(word_count(file_tokens))
你可能在找 将代码移动到函数中,然后使用
for subdir, dirs, files in os.walk(rootdir):
for file in files:
要对Python=>3.6的每个文件调用函数,请使用操作系统
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
# print(os.path.join(directory, filename))
continue
else:
continue
@adlopez15:…它还将处理子目录中的文件。