【问题标题】:Python re.findall() Capitalized Words including ApostrophesPython re.findall() 大写单词,包括撇号
【发布时间】:2018-01-20 04:48:20
【问题描述】:

我在完成正则表达式教程时遇到了麻烦,该教程使用“在 my_string 中查找所有大写单词并打印结果”引用了该问题的单词,其中一些单词带有撇号。

原始字符串:

In [1]: my_string
Out[1]: "Let's write RegEx!  Won't that be fun?  I sure think so.  Can you 
find 4 sentences?  Or perhaps, all 19 words?"

当前尝试:

# Import the regex module
import re
# Find all capitalized words in my_string and print the result
capitalized_words = r"((?:[A-Z][a-z]+ ?)+)"
print(re.findall(capitalized_words, my_string))

当前结果:

['Let', 'RegEx', 'Won', 'Can ', 'Or ']

我认为期望的结果是:

['Let's', 'RegEx', 'Won't', 'Can't', 'Or']

您如何从 r"((?:[A-Z][a-z]+ ?)+)" 到在 Let's, Won't 和 Can't 的末尾同时选择 's 和 't所有试图捕捉的东西都应该有一个撇号?

【问题讨论】:

  • [A-Z][a-z]+ 表示“A 和 Z 以及 a 和 z 之间的所有字母”。定义的范围不包括撇号。将它们添加到正则表达式中。

标签: python regex python-3.x


【解决方案1】:

只需在第二个括号组中添加一个撇号:

capitalized_words = r"((?:[A-Z][a-z']+)+)"

【讨论】:

  • " ?"的空格也不需要了。
  • 本教程从 [a-z] 开始,\w+ 这样做是为了编写一个表达式,它没有解释如何组合基础知识,所以我通过搜索在我的原始帖子中找到了这个表达式。不幸的是,我认为这个问题想要作为输出,你的答案完成了,并不是本教程的预期结果。我完全忘记了以我开头的句子,我看看我是否能理解一种方法来捕捉它。
【解决方案2】:

我想你可以在[a-z'] 组中添加一个小撇号。 所以它会像((?:[A-Z][a-z']+ ?)+)

希望有效

【讨论】:

    【解决方案3】:

    虽然您有答案,但我想使用nltk 提供更“真实”的解决方案:

    from nltk import sent_tokenize, regexp_tokenize
    
    my_string = """Let's write RegEx!  Won't that be fun?  I sure think so.  Can you 
    find 4 sentences?  Or perhaps, all 19 words?"""
    
    sent = sent_tokenize(my_string)
    print(len(sent))
    # 5
    
    pattern = r"\b(?i)[a-z][\w']*"
    print(len(regexp_tokenize(my_string, pattern)))
    # 19
    

    而且 imo,这是 5 个句子,而不是 4 个句子,除非对句子有特殊要求。

    【讨论】:

    • 您将不得不向编写教程的人投诉以解决该问题。
    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 2020-06-03
    • 2019-08-25
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 2021-04-17
    相关资源
    最近更新 更多