Skip to main content
 首页 » 编程设计

python之如何在 Python 中存储 txt 文件中的前 N 个字符串

2025年01月19日22lhb25

我想弄清楚如何从一个 txt 文件中获取前 N 个字符串,并将它们存储到一个数组中。现在,我有代码从一个 txt 文件中获取每个字符串,用空格分隔符分隔,并将其存储到一个数组中。但是,我希望只能从中获取前 N 个字符串,而不是每个字符串。这是我的代码(我是在命令提示符下执行的):

import sys 
f = open(sys.argv[1], "r") 
contents = f.read().split(' ') 
f.close() 

我确定我唯一需要修复的行是:

contents = f.read().split(' ') 

我只是不确定如何在这里将它限制为 N 个字符串。

请您参考如下方法:

如果文件真的很大,但又不太大——也就是说,大到您不想读取整个文件(尤其是在文本模式下或作为行列表),但又不会大到你不能将它分页到内存中(这意味着在 32 位操作系统上不到 2GB,但在 64 位操作系统上更多),你可以这样做:

import itertools 
import mmap 
import re 
import sys 
 
n = 5 
 
# Notice that we're opening in binary mode. We're going to do a 
# bytes-based regex search. This is only valid if (a) the encoding 
# is ASCII-compatible, and (b) the spaces are ASCII whitespace, not 
# other Unicode whitespace. 
with open(sys.argv[1], 'rb') as f: 
    # map the whole file into memory--this won't actually read 
    # more than a page or so beyond the last space 
    m = mmap.mmap(f.fileno(), access=mmap.ACCESS_READ) 
 
    # match and decode all space-separated words, but do it lazily... 
    matches = re.finditer(r'(.*?)\s', m) 
    bytestrings = (match.group(1) for match in matches) 
    strings = (b.decode() for b in bytestrings) 
 
    # ... so we can stop after 5 of them ... 
    nstrings = itertools.islice(strings, n) 
 
    # ... and turn that into a list of the first 5 
    contents = list(nstrings) 

显然,您可以将步骤组合在一起,如果需要,甚至可以将整个过程塞进一个巨大的单行文件中。 (一个惯用的版本将介于那个极端和这个极端之间。)