Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python 2.7.5中从文本文件中提取字符串_Python_Regex_Python 2.7 - Fatal编程技术网

在python 2.7.5中从文本文件中提取字符串

在python 2.7.5中从文本文件中提取字符串,python,regex,python-2.7,Python,Regex,Python 2.7,您好,我是python新手,希望您能帮助我。我有一个文本文件(称之为data.txt),其中包含基因编号的数据,以及相应的rs编号和一些距离度量。数据如下所示: rs1982171 55349 40802 rs6088650 55902 38550 rs1655902 3105 12220 rs1013677 55902 0 rs6088650 55902 38550

您好,我是python新手,希望您能帮助我。我有一个文本文件(称之为data.txt),其中包含基因编号的数据,以及相应的rs编号和一些距离度量。数据如下所示:

   rs1982171     55349     40802

   rs6088650     55902     38550

   rs1655902     3105      12220

   rs1013677     55902      0
    rs6088650    55902     38550

    rs1655902    3105      12220

    rs1013677    55902     0
其中第一列是rs编号,第二列是基因编号,第三列是距离度量。数据要大得多,但希望上面的内容能让您了解数据集。我想做的是找到与某个基因相对应的所有rs编号。例如,对于上面的数据集,基因55902={rs6088650,rs1013677}。理想情况下,我希望我的代码能够找到与给定基因对应的所有rs编号。由于我现在无法做到这一点,因此我编写了一个简短的代码,给出data.txt文件中包含字符串“55902”的行:

  import re
  data=open("data.txt","r")
  for line in data:
      line=line.rstrip()
      if re.search("55902",line):
      print line
此代码的问题在于输出类似于:

   rs1982171     55349     40802

   rs6088650     55902     38550

   rs1655902     3105      12220

   rs1013677     55902      0
    rs6088650    55902     38550

    rs1655902    3105      12220

    rs1013677    55902     0
我希望我的代码忽略rs号码中的字符串“55902”。换句话说,我不需要我的代码来输出上面输出的第二行,因为基因号不是55902。我希望我的输出是:

       rs6088650     55902   38550

       rs1013677     55902   0
如何修改上述代码以实现我的目标。任何帮助都将不胜感激。提前谢谢

您可以使用,来匹配整词搜索:

>>> import re
>>> re.search(r"\b55902\b", "rs1655902     3105      12220")
>>> re.search(r"\b55902\b", "rs6088650     55902     38550")
<_sre.SRE_Match object at 0x7f82594566b0>

使用功能更强大的正则表达式可以轻松地实现这一点。一种可能的快速解决方案是使用以下格式的正则表达式:

r'\b55902\b'

\b
是单词边界。

这里不需要正则表达式,因为您只需要一个简单的静态序列。这一行:

if re.search("55902",line):
可以表示为:

if "55902" in line:
如果只想检查第二列,请先拆分该行:

if '55902' in line.split()[1]:
由于您现在已经检查了正确的列,请检查是否相等,而不是成员资格:

if line.split()[1] == '55902':

如果要使用
regex
,则可以使用
match
search
以及单词boundary
\b
作为

x = "   rs1982171     55349     40802".strip()

if (re.match(r"\b55349\b", x.split()[1])):
    print x

根据您想收集多少不同基因的rs编号,您最好将所有数据放到
数据框中进行分析。谢谢您的建议!