【问题标题】:How to find words ending with ing如何找到以ing结尾的单词
【发布时间】:2015-06-23 04:31:12
【问题描述】:

我正在寻找以 ing 结尾的单词并打印它们,我当前的代码打印出 ing 而不是单词。

#match all words ending in ing
import re
expression = input("please enter an expression: ")
print(re.findall(r'\b\w+(ing\b)', expression))

所以如果我们输入一个表达式:sharing all the information you are hearing

我想打印出['sharing', 'hearing'] 相反,我将 ['ing', 'ing'] 打印出来

有没有快速的方法来解决这个问题?

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    您的捕获分组错误,请尝试以下操作:

    >>> s="sharing all the information you are hearing"
    >>> re.findall(r'\b(\w+ing)\b',s)
    ['sharing', 'hearing']
    

    您也可以在列表理解中使用str.endswith 方法:

    >>> [w for w in s.split() if w.endswith('ing')]
    ['sharing', 'hearing']
    

    【讨论】:

      【解决方案2】:

      括号“捕获”字符串中的文本。你有'(ing\b)',所以只有ing 被捕获。移动左括号,使其包含您想要的整个字符串:r'\b(\w+ing)\b'。看看有没有帮助。

      【讨论】:

        【解决方案3】:
        sentence = 'sharing all the information you are hearing'
        # spit so we have list of words from sentence
        words =  sentence.split(' ')
        
        
        ending_with('ing',words)
        
        def ending_with(ending, words):
            # loop through words
            for word in words:
                # if word has ends with ending
                if word.endswith(ending):
                    # print
                    print word
        

        【讨论】:

          【解决方案4】:

          试试这个。它会工作的!

          import re
          expression = input("please enter an expression: ")
          pattern = "\w+ing"
          result = re.findall(pattern, expression)
          print(result)
          

          【讨论】:

            猜你喜欢
            • 2023-04-11
            • 1970-01-01
            • 1970-01-01
            • 2016-10-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-02
            相关资源
            最近更新 更多