根据字符串拆分文件
我想把一个大文件拆分成一个个小的部分。每个部分都是以“//”这个字符结尾的。所以当我尝试使用
#!/usr/bin/python
import sys,os
uniprotFile=open("UNIPROT-data.txt") #read original alignment file
uniprotFileContent=uniprotFile.read()
uniprotFileList=uniprotFileContent.split("//")
for items in uniprotFileList:
seqInfoFile=open('%s.dat'%items[5:14],'w')
seqInfoFile.write(str(items))
的时候,我发现文件里还有其他地方也有“//”(比如http://www.uniprot.org/terms),这样就导致它在那些地方也被拆分了,最终我得不到我想要的结果。我试着用正则表达式,但没能搞明白。
5 个回答
0
你似乎在用错的字符进行分割。根据你的问题,你应该用 r"\\" 来分割,而不是 "//"。打开一个命令行窗口,检查一下你正在使用的字符串。你会看到类似这样的内容:
>>> "\\"
'\\'
>>> "\"
SyntaxError
>>> r"\"
'\\'
>>> "//"
'//'
所以,你可以使用 "\\" 或者 r"\\"(我推荐使用 r"\\",这样在分割和正则表达式操作时会更清晰)。
3
我正在使用修改过的分割模式的代码,这对我来说运行得很好:
#!/usr/bin/python
import sys,os
uniprotFile = open("UNIPROT-data.txt")
uniprotFileContent = uniprotFile.read()
uniprotFileList = uniprotFileContent.split("//\n")
for items in uniprotFileList:
seqInfoFile = open('%s.dat' % items[5:17], 'w')
seqInfoFile.write(str(items))
7
使用一个正则表达式,只有在//
前面没有:
的时候才进行分割。
import re
myre = re.compile("(?<!:)//")
uniprotFileList = myre.split(uniprotFileContent)