搜索文件中的特定字符串并将后面的字符串保存在python中的文件中

时间:2017-11-28 11:42:48

标签: python string search

我想从我拥有的文件中保存一些特定数据,它看起来像是这样的:

[StagePositionMapFile]
[StageMapPosition]
XCoordinate=-1.37525e-003
YCoordinate=-5.52599999999999e-003
ZCoordinate=9.96477272727273e-003
RCoordinate=-2.18201293271677
TCoordinate=-1.19239958528248e-004
PositionName=Position 14

[StageMapPosition]
XCoordinate=-1.40625e-003
YCoordinate=-5.01925000000001e-003
ZCoordinate=9.96477272727273e-003
RCoordinate=-2.18201293271677
TCoordinate=-9.31942430672605e-005
PositionName=Position 13

[StageMapPosition]
XCoordinate=-1.387625e-003
YCoordinate=-4.68562500000001e-003
ZCoordinate=9.96477272727273e-003
RCoordinate=-2.18201293271677
TCoordinate=-9.31942430672605e-005
PositionName=Position 12 

我只想在XCoordinate和YCoordinate之后保留数据,所以我所做的就是读取文件并根据等号将其拆分,然后在我的代码中看到lign return:

   with open("E:/WOrk/PHD/SEM_images/NS65/Systematic_study/100_uM /NS_65_6_K_15_mM_100_uM_B4_66%_60_s/positionw.txt","r") as openfile:



    for line in openfile :


        s=line.split("=")


        for index,line in enumerate(s) :


            list=[index,line]
            list2=line.split("\n")

但是我真的不明白line.split(“\ n”)中的内容是什么,因为我只得到一个带有=符号后面的值的列表,而我没有在列表中获得XCoordinate字符串。

第二件事就是那时我想说当在列表中找到XCoordinate后取字符串。我知道我可以使用枚举和索引来实现。但是,当我只是试图打印时,如果XCoordinate在那里,它就不会打印任何东西......

最后我想要这样的东西:

(values of XCoordinate)         (values of YCoordinate)
-1.37525e-003                    -5.52599999999999e-003

编辑:

我更改了代码并列出了文件中所有单词的列表:

with open("E:/WOrk/PHD/SEM_images/NS65/Systematic_study/100_uM/NS_65_6_K_15_mM_100_uM_B4_66%_60_s/positionw.txt","r") as openfile:


        separate=list()
        for line in openfile :


            s=line.split("=")


            for element in s :

                element2=element.split("\n")

                for value in element2: 


                    separate.append(value)

        for index,valeur in enumerate(separate) :

            chaine="XCoordinate"
            print(valeur)
            print("stop")
            if chaine in valeur :

                print("true")

现在每次XCoordinate出现时我都应该成真,但事实并非如此:/

感谢您的帮助。

Mathais

1 个答案:

答案 0 :(得分:0)

我认为这个脚本适合你

text=''
    regx =re.compile('((XCoordinate=[-]{0,1}[0-9]*.[0-9]*e-[0-9]*)\n(YCoordinate=[-]{0,1}[0-9]*.[0-9]*e-[0-9]*))')
    with open('test.txt', 'r+') as file:
        for line in file:
            text += line

    find = re.findall(regx,text)
    print ('findaa  ', find)

,out将是

  

[( 'x坐标= -1.37525e-003 \ nYCoordinate = -5.52599999999999e-003',   'XCoordinate = -1.37525e-003','YCoordinate = -5.52599999999999e-003'),   ( 'x坐标= -1.40625e-003 \ nYCoordinate = -5.01925000000001e-003',   'XCoordinate = -1.40625e-003','YCoordinate = -5.01925000000001e-003'),   ( 'x坐标= 1.387625e-003 \ nYCoordinate = -4.68562500000001e-003',   'XCoordinate = 1.387625e-003','YCoordinate = -4.68562500000001e-003')]