首页 > 解决方案 > 从多个文本文件中读取一定数量的单词并保存为新文件

问题描述

我有数百本书的文本文件(file001.txt、file002.txt 等),我想从每个文件中读取前 3,000 个单词并将其另存为新文件(例如 file001_first3k.txt、file002_first3k.txt)。

我已经看到了 Mac 和 Linux 的终端解决方案(我都有),但它们似乎是用于显示到终端窗口和设置数量的字符,而不是单词。

在 Python 中发布这个似乎比终端更有可能在这里找到解决方案,而且我有一些 Python 经验。

标签: python

解决方案


希望这会让你开始,它假设可以分割空格以确定单词的数量。

import os
import sys

def extract_first_3k_words(directory):
    original_file_suffix = ".txt"
    new_file_suffix = "_first3k.tx"
    filenames = [f for f in os.listdir(directory)
        if f.endswith(original_file_suffix) and not f.endswith(new_file_suffix)]

    for filename in filenames:
        with open(filename, "r") as original_file:

            # Get the first 3k words of the file
            num_words = 3000
            file_content = original_file.read()
            words = file_content.split(" ")
            first_3k_words = " ".join(words[:num_words])

            # Write the new file
            new_filename = filename.replace(original_file_suffix, new_file_suffix)
            with open(new_filename, "w") as new_file:
                new_file.write(first_3k_words)

            print "Extracted 3k words from: %s to %s" % (filename, new_filename)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Usage: python file_splitter.py <target_directory>"
        exit()
    directory = sys.argv[1]
    extract_first_3k_words(directory)

推荐阅读