我制作了一个脚本,将一个长文件分割成多个小文件。当正好有4个整数时,它总是分裂。我想通过声明正好有4个整数来改进它,但只在行首。你知道吗
样本输入
1020
200123242151111231 bla bla bla
200123331231231441 bla bla bla
1030
200123242151111231 bla bla bla
200123331231231441 bla bla bla
希望输出的是上述内容分为:
200123242151111231 bla bla bla
200123331231231441 bla bla bla
以及
200123242151111231 bla bla bla
200123331231231441 bla bla bla
当bla的其中一个值是4个整数时,它会添加一个额外的分割。如何确保重新拆分函数只检查一行的前4或5个值。你知道吗
import re
file = open('testnew.txt', 'r')
i=0
for x in re.split(r"\b[0-9]{4}\s+", file.read()):
f = open('%d.txt' %i,'w')
f.write(x)
f.close()
print (x,i)
i = i+1
逐行阅读会很好。您可以检查字符串长度是否为4,然后跳过它。你知道吗
逐行读取文件可能更好。这样,如果文件太大,您就不会遇到内存过载的问题,而且您还可以对行本身运行4位检查,而不会出现尴尬的拆分。你知道吗
测试文件:
结果:
1234.txt文件
3267.txt文件
1111.txt
^匹配字符串的开头
$匹配字符串的结尾
findall返回所有匹配项的列表,如果使用(捕获组),它将返回捕获组
(?:)是非捕获组
*是贪婪的,*?不是
此解决方案应适用于:
相关问题 更多 >
编程相关推荐