我需要为python中的单词做正则表达式。我得到一个句子,我需要检查其中是否有单词。
“Hello”,“It‘s”这两个词将会出现在列表中。“--妈妈”或“-妈妈”这两个词不在列表中。但是“妈妈”将出现在列表中,因为它将“-”和“妈妈”分开,所以“妈妈”要考虑“我如何才能得到以”-“开头的单词,而不是像”--妈妈“这样的单词?”
def getWord():
return"((^[A-Z])?[a-z]+)((\-[a-z]*)*)(\')?[a-z]{0,2}"
text=r"""Hello Bob! It's Mary, your mother-in-law, the mistake is your parents'! --Mom""")
com = re.compile(rf"""((?P<WORD>{getWord()})), """,re.MULTILINE | re.IGNORECASE | re.VERBOSE | re.UNICODE)
lst=[(v, k) for match in com.finditer(text)
for k, v in match.groupdict().items()
if v is not None and k != 'SPACE']
print(lst)发布于 2021-10-30 06:13:46
你可能把这变得过于复杂了,在\w+上的正则表达式find all搜索已经接近你想要的结果了。为了允许所有格,只需将's作为每个单词后的可选结尾即可。此外,为了排除前面没有空格(或者在字符串的最开始处)的单词,我们可以使用否定的后缀(?<!\S)作为前缀。
text = "Hello Bob! It's Mary, your mother-in-law, the mistake is your parents! --Mom"
words = re.findall(r"(?<!\S)\w+(?:'s)?", text)
print(words)这将打印:
['Hello', 'Bob', "It's", 'Mary', 'your', 'mother', 'in', 'law', 'the', 'mistake', 'is',
'your', 'parents']https://stackoverflow.com/questions/69777192
复制相似问题