gpt4 book ai didi

python - 正则表达式在 Python 中拆分单词

转载 作者:IT老高 更新时间:2023-10-28 21:00:37 25 4
gpt4 key购买 nike

我正在设计一个正则表达式来拆分给定文本中的所有实际单词:


输入示例:

"John's mom went there, but he wasn't there. So she said: 'Where are you'"


预期输出:

["John's", "mom", "went", "there", "but", "he", "wasn't", "there", "So", "she", "said", "Where", "are", "you"]



我想到了这样的正则表达式:

"(([^a-zA-Z]+')|('[^a-zA-Z]+))|([^a-zA-Z']+)"

在Python中拆分后,结果包含None项和空格。

如何去掉 None 项?为什么空格不匹配?


编辑:
在空格上拆分,将给出如下项目: ["there."]
并且拆分非字母,将给出如下项目: ["John","s"]
除了 ' 之外的非字母拆分,将给出如下项目:["'Where","you'"]

最佳答案

您可以使用字符串函数来代替正则表达式:

to_be_removed = ".,:!" # all characters to be removed
s = "John's mom went there, but he wasn't there. So she said: 'Where are you!!'"

for c in to_be_removed:
s = s.replace(c, '')
s.split()

但是,在您的示例中,您不想删除 John's 中的撇号,但希望在 you!!' 中删除撇号。所以字符串操作在那个时候失败了,你需要一个微调的正则表达式。

编辑:可能一个简单的正则表达式可以解决您的问题:

(\w[\w']*)

它将捕获所有以字母开头的字符并继续捕获,而下一个字符是撇号或字母。

(\w[\w']*\w)

第二个正则表达式是针对一个非常特殊的情况...。第一个正则表达式可以捕获像 you' 这样的词。这将避免这种情况,并且仅在 is 在单词内(不在开头或结尾)时才捕获撇号。但是在那一点上,出现了一种情况,您无法使用第二个正则表达式捕获撇号 Moss' mom。您必须决定是否在以 s 结尾的名称中捕获尾随撇号并定义所有权。

例子:

rgx = re.compile("([\w][\w']*\w)")
s = "John's mom went there, but he wasn't there. So she said: 'Where are you!!'"
rgx.findall(s)

["John's", 'mom', 'went', 'there', 'but', 'he', "wasn't", 'there', 'So', 'she', 'said', 'Where', 'are', 'you']

更新 2:我在我的正则表达式中发现了一个错误!它不能捕获单个字母后跟像 A' 这样的撇号。修复了全新的正则表达式:

(\w[\w']*\w|\w)

rgx = re.compile("(\w[\w']*\w|\w)")
s = "John's mom went there, but he wasn't there. So she said: 'Where are you!!' 'A a'"
rgx.findall(s)

["John's", 'mom', 'went', 'there', 'but', 'he', "wasn't", 'there', 'So', 'she', 'said', 'Where', 'are', 'you', 'A', 'a']

关于python - 正则表达式在 Python 中拆分单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12705293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com