Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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 如何使用findall打印正则表达式的结果?_Python_Regex_Parsing - Fatal编程技术网

Python 如何使用findall打印正则表达式的结果?

Python 如何使用findall打印正则表达式的结果?,python,regex,parsing,Python,Regex,Parsing,对于Python正则表达式来说有点陌生,我正在尝试解析下面的数据 代码 thing = soup.find_all('div', {'class' : 'matchheader'}) thing1 = str(thing) print(thing1) 给我 1. GSL - <b>Global Ship Lease Inc</b> [N/A] - Matched DCIX from 07/27/16 to 12/01/16 </div>, <d

对于Python正则表达式来说有点陌生,我正在尝试解析下面的数据

代码

thing = soup.find_all('div', {'class' : 'matchheader'})
thing1 = str(thing)
print(thing1)
给我

  1. GSL - <b>Global Ship Lease Inc</b> [N/A] - Matched DCIX from 07/27/16 to 12/01/16
  </div>, <div class="matchheader">
  2. SBGI - <b>Sinclair Broadcast Group, Inc.</b> [Media] - Matched DCIX from 07/27/16 to 12/01/16
  </div>, <div class="matchheader">
  3. WSTC - <b>West Corporation</b> [+2] - Matched DCIX from 07/27/16 to 12/01/16
  </div>, <div class="matchheader">
  4. TGNA - <b>TEGNA Inc.</b> [N/A] - Matched DCIX from 07/27/16 to 12/01/16
  </div>, <div class="matchheader">
  5. MLI - <b>MUELLER INDUSTRIES INC</b> [Manufacturing] - Matched DCIX from 07/27/16 to 12/01/16
我期待的结果是

['GSL', 'SBGI', 'WSTC', 'TGNA', 'MLI']
但我得到的结果是

['G', 'D', 'S', 'D', 'W', 'D', 'T', 'T', 'D', 'M', 'U', 'S', 'I', 'D']
我很确定第二个D来自第一行的DCIX

因此,我使用的正则表达式模式、使用re.findall还是打印(匹配),是问题所在


任何帮助都将不胜感激

您的正则表达式将匹配每组连续的大写字母,然后只返回每组的第一个字母。相反,您可能只是想返回这些组中的第一个,每行

您可以改为使用前缀
^.*([A-Z]{2,5})
在行的开头找到最短的序列
^.*.
(对于多行模式,使用
re.M
),后跟一组大写字母
([A-Z]{2,5})
,如果有的话,然后返回该组

>>> re.findall("^.*?([A-Z]{2,5})", thing1, re.M)
['GSL', 'SBGI', 'WSTC', 'TGNA', 'MLI']

如果是包装文本,或者为了确保得到第二行元素(如果类名为空),我建议检查行开头的数字是否存在,并使用以下正则表达式:

r"^[0-9]+[^\w]+([A-Z]{2,5})"

我不完全确定,但也许你想要的是汤。文本?i、 e:

for item in thing:
    thing1=item.text
    print(thing1)
但是,我会这样做:

thing=soup.select('div.matchheader') #returns a list of divs that have a css class 'matchheader'
thing1_list=[]
for item in thing:
    thing1_list.append(item.getText())

希望这有帮助

您当前的正则表达式也与DCIX匹配,请尝试以下方法:在第1组中匹配您想要的。就是这样!非常感谢@NicolasMaltais你真的很感激。
thing=soup.select('div.matchheader') #returns a list of divs that have a css class 'matchheader'
thing1_list=[]
for item in thing:
    thing1_list.append(item.getText())