将带有正则表达式的文本解析到resu中带有空字符串的列表中

2024-04-24 05:57:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着把一个字符串分解成几个字。你知道吗

    def breakup(text):
        temp = []
        temp = re.split('\W+', text.rstrip())   
        return [e.lower() for e in temp]

字符串示例:

什么是黄色、白色、绿色和凹凸不平的?穿着燕尾服的泡菜

结果:

[“什么”、“s”、“黄色”、“白色”、“绿色”、“和”、“凹凸”、“a”、“泡菜”、“穿着”、“a”、“燕尾服”]

但是当我传递一根像

锁匠怎么像打字机?他们都有很多钥匙!

['how'、'is'、'a'、'locksmith'、'like'、'a'、'typewriter'、'they'、'both'、'have'、'a'、'lot'、'of'、'keys'、'''.]

我想以一种不会在列表中得到空字符串的方式进行解析。你知道吗

传递的字符串将有标点符号等任何想法。你知道吗


Tags: 字符串textrereturndeflowertemp泡菜
3条回答

搜索你想要的东西怎么样:

[ s.lower() for s in
  re.findall(r'\w+',
    "How is a locksmith like a typewritter? They both have a lot of keys!") ]

或者只建立一个列表:

[ s.group().lower() for s in
  re.finditer(r'\w+',
    "How is a locksmith like a typewritter? They both have a lot of keys!") ]

只要改变

return [e.lower() for e in temp]

return [e.lower() for e in temp if e]

还有,那条线

temp = []

不需要,因为您从不使用指定给temp的空列表

这样做有效:

txt='''\
What's yellow, white, green and bumpy? A pickle wearing a tuxedo
How is a locksmith like a typewritter? They both have a lot of keys!'''

import re

for line in txt.splitlines():
    print [word.lower() for word in re.findall(r'\w+', line) if word.strip()]

印刷品:

['what', 's', 'yellow', 'white', 'green', 'and', 'bumpy', 'a', 'pickle', 'wearing', 'a', 'tuxedo']
['how', 'is', 'a', 'locksmith', 'like', 'a', 'typewritter', 'they', 'both', 'have', 'a', 'lot', 'of', 'keys']

相关问题 更多 >