python - 从多个文本文件中读取一定数量的单词并保存为新文件
问题描述
我有数百本书的文本文件(file001.txt、file002.txt 等),我想从每个文件中读取前 3,000 个单词并将其另存为新文件(例如 file001_first3k.txt、file002_first3k.txt)。
我已经看到了 Mac 和 Linux 的终端解决方案(我都有),但它们似乎是用于显示到终端窗口和设置数量的字符,而不是单词。
在 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)
推荐阅读
- django - 检索 get 参数时编码错误
- sql-server - 在个人计算机上使用 SQL Server Express 托管网站
- reactjs - 类型错误无法读取未定义 reactjs 的属性“推送”
- codenameone - 代号一个应用程序无法使用 https 请求与服务器连接
- azure - 使用 ARM 模板为 Azure VM 激活 MSI
- python - Keras - 检索层连接到的层
- asp.net - 如何使用asp gridview链接按钮从数据库下载pdf文件
- java - 聊天片段不更新 recyclerview
- python - 从 Box 下载文件
- vue.js - 为 Vue 组件元素动态添加任意属性?