【问题标题】:Python regex for finding all words in a string [duplicate]用于查找字符串中所有单词的 Python 正则表达式 [重复]
【发布时间】:2016-09-29 08:23:20
【问题描述】:

您好,我是 regex 的新手,我从 python 开始。 我坚持从英语句子中提取所有单词。 到目前为止,我有:

import re

shop="hello seattle what have you got"
regex = r'(\w*) '
list1=re.findall(regex,shop)
print list1

这给出了输出:

['你好','西雅图','什么','有','你']

如果我将正则表达式替换为

regex = r'(\w*)\W*'

然后输出:

['你好','西雅图','什么','有','你','得到','']

而我想要这个输出

['你好','西雅图','什么','有','你','得到']

请指出我哪里出错了。

【问题讨论】:

    标签: python regex words sentence


    【解决方案1】:

    使用字边界\b

    import re
    
    shop="hello seattle what have you got"
    regex = r'\b\w+\b'
    list1=re.findall(regex,shop)
    print list1
    
    OP : ['hello', 'seattle', 'what', 'have', 'you', 'got']
    

    或者只是\w+就足够了

    import re
    
    shop="hello seattle what have you got"
    regex = r'\w+'
    list1=re.findall(regex,shop)
    print list1
    
    OP : ['hello', 'seattle', 'what', 'have', 'you', 'got']
    

    【讨论】:

      猜你喜欢
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 2017-06-23
      • 2018-03-10
      • 2011-06-06
      • 1970-01-01
      相关资源
      最近更新 更多