Python - 按分隔符出现次数拆分大字符串
Python - Splitting a large string by number of delimiter occurrences
我还在学习Python,我有个问题没能解决。我有一个很长的字符串(数百万行),我想根据指定的分隔符出现次数将其拆分成更小的字符串长度。
例如:
ABCDEF
//
GHIJKLMN
//
OPQ
//
RSTLN
//
OPQR
//
STUVW
//
XYZ
//
在这种情况下,我想根据“//”和 return 分隔符第 n 次出现之前的所有行的字符串进行拆分。
因此将字符串按 // 按 1 拆分的输入将 return:
ABCDEF
将字符串按 // 按 2 拆分的输入将 return:
ABCDEF
//
GHIJKLMN
将字符串按 // 按 3 拆分的输入将 return:
ABCDEF
//
GHIJKLMN
//
OPQ
等等... 但是,当我简单地尝试拆分整个字符串并通过"/ /" 并只处理单独的索引。 (我遇到了内存错误)也许 Python 不能一次处理这么多行?所以我不能那样做。
我正在寻找一种方法,当我可能只需要 100 个时,我不需要将整个字符串拆分成十万个索引,而是从头开始直到某个点,停止并return 它之前的所有内容,我认为它也可能更快?我希望我的问题尽可能清楚。
有没有一种简单或优雅的方法来实现这一点?谢谢!
例如:
i = 0
s = ""
fd = open("...")
for l in fd:
if l[:-1] == delimiter: # skip last '\n'
i += 1
if i >= max_split:
break
s += l
fd.close()
作为一种更有效的方法,您可以阅读由定界符分隔的第一个 N
行,因此如果您确定所有行都由定界符分隔,则可以使用 itertools.islice
来执行工作:
from itertools import islice
with open('filename') as f :
lines = islice(f,0,2*N-1)
看到你的问题我想到的方法是使用for循环
您将字符串分成几个(例如您调用的 100)并遍历子字符串。
thestring = "" #your string
steps = 100 #length of the strings you are going to use for iteration
log = 0
substring = thestring[:log+steps] #this is the string you will split and iterate through
thelist = substring.split("//")
for element in thelist:
if(element you want):
#do your thing with the line
else:
log = log+steps
# and go again from the start only with this offset
现在您可以遍历整个 200 万(!)行字符串中的所有元素。
这里最好的办法实际上是从中创建一个递归函数(如果这是你想要的):
thestring = "" #your string
steps = 100 #length of the strings you are going to use for iteration
def iterateThroughHugeString(beginning):
substring = thestring[:beginning+steps] #this is the string you will split and iterate through
thelist = substring.split("//")
for element in thelist:
if(element you want):
#do your thing with the line
else:
iterateThroughHugeString(beginning+steps)
# and go again from the start only with this offset
由于您正在学习 Python,因此对完整的动态解决方案建模将是一项挑战。这是一个关于如何建模的概念。
注意:以下代码片段仅适用于给定格式 is/are 的文件(请参阅问题中的 'For Instance')。因此,它是一个静态解决方案。
num = (int(input("Enter delimiter: ")) * 2)
with open("./data.txt") as myfile:
print ([next(myfile) for x in range(num-1)])
既然有了思路,就可以使用模式匹配等了。
如果您想使用文件而不是内存中的字符串,这里是另一个答案。
这个版本是作为一个函数编写的,它读取行并立即打印出来,直到找到指定数量的分隔符(不需要额外的内存来存储整个字符串)。
def file_split(file_name, delimiter, n=1):
with open(file_name) as fh:
for line in fh:
line = line.rstrip() # use .rstrip("\n") to only strip newlines
if line == delimiter:
n -= 1
if n <= 0:
return
print line
file_split('data.txt', '//', 3)
您可以使用它来将输出写入新文件,如下所示:
python split.py > newfile.txt
通过一些额外的工作,您可以使用 argparse
向程序传递参数。
我还在学习Python,我有个问题没能解决。我有一个很长的字符串(数百万行),我想根据指定的分隔符出现次数将其拆分成更小的字符串长度。
例如:
ABCDEF
//
GHIJKLMN
//
OPQ
//
RSTLN
//
OPQR
//
STUVW
//
XYZ
//
在这种情况下,我想根据“//”和 return 分隔符第 n 次出现之前的所有行的字符串进行拆分。
因此将字符串按 // 按 1 拆分的输入将 return:
ABCDEF
将字符串按 // 按 2 拆分的输入将 return:
ABCDEF
//
GHIJKLMN
将字符串按 // 按 3 拆分的输入将 return:
ABCDEF
//
GHIJKLMN
//
OPQ
等等... 但是,当我简单地尝试拆分整个字符串并通过"/ /" 并只处理单独的索引。 (我遇到了内存错误)也许 Python 不能一次处理这么多行?所以我不能那样做。
我正在寻找一种方法,当我可能只需要 100 个时,我不需要将整个字符串拆分成十万个索引,而是从头开始直到某个点,停止并return 它之前的所有内容,我认为它也可能更快?我希望我的问题尽可能清楚。
有没有一种简单或优雅的方法来实现这一点?谢谢!
例如:
i = 0
s = ""
fd = open("...")
for l in fd:
if l[:-1] == delimiter: # skip last '\n'
i += 1
if i >= max_split:
break
s += l
fd.close()
作为一种更有效的方法,您可以阅读由定界符分隔的第一个 N
行,因此如果您确定所有行都由定界符分隔,则可以使用 itertools.islice
来执行工作:
from itertools import islice
with open('filename') as f :
lines = islice(f,0,2*N-1)
看到你的问题我想到的方法是使用for循环 您将字符串分成几个(例如您调用的 100)并遍历子字符串。
thestring = "" #your string
steps = 100 #length of the strings you are going to use for iteration
log = 0
substring = thestring[:log+steps] #this is the string you will split and iterate through
thelist = substring.split("//")
for element in thelist:
if(element you want):
#do your thing with the line
else:
log = log+steps
# and go again from the start only with this offset
现在您可以遍历整个 200 万(!)行字符串中的所有元素。
这里最好的办法实际上是从中创建一个递归函数(如果这是你想要的):
thestring = "" #your string
steps = 100 #length of the strings you are going to use for iteration
def iterateThroughHugeString(beginning):
substring = thestring[:beginning+steps] #this is the string you will split and iterate through
thelist = substring.split("//")
for element in thelist:
if(element you want):
#do your thing with the line
else:
iterateThroughHugeString(beginning+steps)
# and go again from the start only with this offset
由于您正在学习 Python,因此对完整的动态解决方案建模将是一项挑战。这是一个关于如何建模的概念。
注意:以下代码片段仅适用于给定格式 is/are 的文件(请参阅问题中的 'For Instance')。因此,它是一个静态解决方案。
num = (int(input("Enter delimiter: ")) * 2)
with open("./data.txt") as myfile:
print ([next(myfile) for x in range(num-1)])
既然有了思路,就可以使用模式匹配等了。
如果您想使用文件而不是内存中的字符串,这里是另一个答案。
这个版本是作为一个函数编写的,它读取行并立即打印出来,直到找到指定数量的分隔符(不需要额外的内存来存储整个字符串)。
def file_split(file_name, delimiter, n=1):
with open(file_name) as fh:
for line in fh:
line = line.rstrip() # use .rstrip("\n") to only strip newlines
if line == delimiter:
n -= 1
if n <= 0:
return
print line
file_split('data.txt', '//', 3)
您可以使用它来将输出写入新文件,如下所示:
python split.py > newfile.txt
通过一些额外的工作,您可以使用 argparse
向程序传递参数。