用Python从.txt文件中获取前1000个或定义的字数最简单的方法是什么?

2024-05-17 05:06:57 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是问题的上下文:我有一个.txt文件,其中逐行包含经文的诗句。每行包含不同数量的单词。不管怎样,有没有一种方法可以将文件中的前1000个单词取出来,创建一个不同的文件(例如块1)并将信息输入到该文件中,然后用下1000个单词创建另一个文件,从中取下前1000个单词,以此类推,同时忽略章节数? 一个回应将非常感谢,因为我这样做的人统计项目。你知道吗


Tags: 文件项目方法txt信息数量诗句单词
2条回答

这应该起作用:

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 ))
with open('scripture_verses.txt') as f:
    words = []
    i = 0
    for line in f:
        for word in line.split():
            words.append(word)
            i += 1
            if i % 1000 == 0:
                with open('out{}.txt'.format(i // 1000), 'w') as out:
                    print(' '.join(words), file=out)
                words = []
    else:
        with open('out{}.txt'.format(i // 1000 + 1), 'w') as out:
            print(' '.join(words), file=out)
        words = []

相关问题 更多 >