[英]match reoccurring words in string using regex in Python
我正在尝试匹配字符串中重复出现的单词
我试过re.findall( r"(\\b(\\w+)\\b)((?=.*)\\1)+ , stringToCheck )
但无济于事。
对于像"ball ball glass table ball glass chair"
这样的字符串,我想使用正则表达式提取ball, ball, glass, ball, glass
。 有人可以帮忙吗?
您可以使用正则表达式和列表理解来解决此问题,如下所示:
In [43]: s = "ball ball glass table ball glass chair"
In [68]: splitted = re.findall(r"\w+", s)
In [69]: [item for item in splitted if splitted.count(item) > 1]
Out[69]: ['ball', 'ball', 'glass', 'ball', 'glass']
如果您不拘泥于使用正则表达式,则可以使用以下代码轻松完成此操作(如问题评论所建议):
from collections import Counter
cnt = Counter()
example_string = "ball ball glass table ball glass chair"
word_list = example_string.split(" ")
for word in word_list:
cnt[word] += 1
print(cnt)
然后可以对此进行过滤,以仅给出计数大于1的那个。
filtered = {k:v for (k,v) in cnt.items() if v > 1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.