这是问题的上下文:我有一个 .txt 文件,其中逐行包含经文。每行包含不同数量的单词。不管怎样,有没有办法把文件的前 1000 个单词,创建一个不同的文件(例如 block 1)并将信息输入该文件,然后用接下来的 1000 个单词创建另一个文件,前 1000 个单词来自被拍了等等,同时也忽略了章节的数量? 非常感谢您的回复,因为我正在为一个人员统计项目执行此操作。
最佳答案
这应该有效:
from string import ascii_letters
with open( 'scripture.txt' ) as fin :
text = fin.read()
valid_characters = ascii_letters + '\n\t '
text = ''.join( t for t in text if t in valid_characters )
text = text.split()
for i in range(len(text)//1000) :
with open( 'part_%03d.txt' % i, 'w') as fout :
thousand_words = text[i*1000:min((i+1)*1000,len(text))]
fout.write( ' '.join( thousand_words ))
关于python - 使用 Python 从 .txt 文件中获取前 1000 个或定义数量的单词的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59257911/