Python 将带有正则表达式的文本解析到结果为空字符串的列表中
我正试图把一个字符串分解成几个字Python 将带有正则表达式的文本解析到结果为空字符串的列表中,python,regex,Python,Regex,我正试图把一个字符串分解成几个字 def breakup(text): temp = [] temp = re.split('\W+', text.rstrip()) return [e.lower() for e in temp] 字符串示例: 什么是黄色、白色、绿色和凹凸不平的?穿着燕尾服的泡菜 结果: [“什么”、“s”、“黄色”、“白色”、“绿色”、“凹凸”、“a”、“泡菜”、“穿着”、“a”、“燕尾服”] 但是当我传递一根
def breakup(text):
temp = []
temp = re.split('\W+', text.rstrip())
return [e.lower() for e in temp]
字符串示例:
什么是黄色、白色、绿色和凹凸不平的?穿着燕尾服的泡菜
结果:
[“什么”、“s”、“黄色”、“白色”、“绿色”、“凹凸”、“a”、“泡菜”、“穿着”、“a”、“燕尾服”]
但是当我传递一根像
锁匠和打字机有什么相似之处?他们都有很多钥匙强>
['how','is','a','lockmith','like','a','typewriter','this','two','have','a','lot','of','keys',''.]
我想以一种不会在列表中得到空字符串的方式进行解析
传递的字符串将包含标点符号等。任何想法。只要更改即可
return [e.lower() for e in temp]
到
还有,线路
temp = []
不需要,因为您从不使用登录到
temp
的空列表,为什么不在列表中检查此项
return [e.lower() for e in temp if len(e) > 0]
或者是那些书呆子
return [e.lower() for e in temp if e]
搜索你想要的东西怎么样:
[ 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!") ]
这项工作:
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']
你可以做:
'How is a locksmith <blah> a lot of keys!'.rstrip('!?.').split()
“锁匠怎么会有这么多钥匙!”。rstrip(“!?”).split()
在您的特殊情况下:
def breakup(text):
temp = []
temp = re.split('\W+', text.rstrip())
return [e.lower() for e in temp if e]
更普遍的解决办法是:
>>> re.findall('\w+', 'How is a locksmith like a typewritter? They both have a lot of keys!')
>>> ['How', 'is', 'a', 'locksmith', 'like', 'a', 'typewritter', 'They', 'both', 'have', 'a', 'lot', 'of', 'keys']
+1这比拆分然后过滤更简单。谢谢你的回答。是的,我发现
\W
很奇怪。但可能OP需要拆分而不是搜索(这可能只是一个简化的例子)。在这种情况下,findall似乎确实比split更合适。预期的结果是一个包含标记化或解析文本的列表,那么finall为什么比split好呢?“if len(e)>0”不是pythonic,“if e”会是enough@DmitryVakhrushev考虑到这个问题,我想知道新手是否可以通过更明确地了解你的答案,从而从理解引擎盖下发生的事情中获益。教新手坏习惯是一种坏习惯。@DmitryVakhrushev我看不出len(e)
是一种坏习惯。关于这里正在发生的事情,它更为明确,但绝不是不正确的。谢谢你的回答。我想知道我应该选择你的还是JaredPar。正如他提到的len表示空字符串一样?没有必要使用len
,因为空字符串本身就是falsy(这是一个单词吗?)。我建议使用findall
而不是split
。Use应该接受他的回答IMHO。预期的结果是一个包含标记化或解析文本的列表,那么为什么finall比split好呢?我认为这更清楚一点,因为在运行正则表达式后,您不需要过滤(除非您想在除空格之外的其他内容上进行拆分)。OTHO,代码很简单,它可能归结为你个人的喜好,你应该使用哪一个。谢谢你的回答。谢谢你的回答。谢谢你的回答。
>>> re.findall('\w+', 'How is a locksmith like a typewritter? They both have a lot of keys!')
>>> ['How', 'is', 'a', 'locksmith', 'like', 'a', 'typewritter', 'They', 'both', 'have', 'a', 'lot', 'of', 'keys']