【发布时间】:2014-07-23 13:32:34
【问题描述】:
我尝试从文件的每一行中提取第一个字符、第二个数字和第三个字符并存储到三个变量中,分别称为 FirstChar、SecondNum、ThirdChar。
输入文件(MultiPointMutation.txt):
P1T,C11F,E13T
L7A
E2W
预期输出:
FirstChar="PCELE"
SecondNum="1 11 13 7 2"
ThirdChar="TFTAW"
我的代码:
import re
import itertools
ns=map(lambda x:x.strip(),open('MultiplePointMutation.txt','r').readlines())#reading file
for line in ns:
second="".join(re.findall(r'\d+',line))#extract second position numbers
print second # print second nums
char="".join(re.findall(r'[a-zA-Z]',line))#Extract all characters
c=str(char.rstrip())
First=0
Third=1
for index in range(len(c)):
if index==First:
FC=c[index]#here i got all first characters
print FC
First=First+2
if index==Third:
TC=c[index]
print TC
Third=Third+2#here i got all third characters
输出: 在这里,我得到的 FirstCharacter 和 ThirdCharacter 完全正确
FirstChar:
P
C
E
L
E
ThirdChar:
T
F
T
A
W
但问题在于获取 SecondNum:
SecondNum:
11113
7
2
我想提取数字如下:
1
11
13
7
2
注意:在这里,我不想一一打印。我想一一读取这个 SecondNum 变量值以备后用。
【问题讨论】:
标签: python regex string file-io extraction