【发布时间】:2021-05-01 19:47:17
【问题描述】:
所以对于某些文本中的单个单词子串计数,我可以使用some_text.split().count(single_word_substring)。对于某些文本中的多字子字符串计数,我该如何做到这一点?
例子:
text = 'he is going to school. abc is going to school. xyz is going to school.'
to_be_found = 'going to school'
计数应该是 3。
text = 'he is going to school. abc is going to school. xyz is going to school.'
to_be_found = 'going to'
计数应该是 3。
text = 'he is going to school. abc is going to school. xyz is going to school.'
to_be_found = 'go'
计数应为 0。
text = 'he is going to school. abc-xyz is going to school. xyz is going to school.'
to_be_found = 'school'
计数应该是 3。
text = 'he is going to school. abc-xyz is going to school. xyz is going to school.'
to_be_found = 'abc-xyz'
计数应该是 1。
假设 1: 一切都是小写的。
假设 2: 文本可以包含任何内容。
假设 3: to be found 也可以包含任何东西。比如car with 4 passengers、xyz & abc等。
注意:基于 REGEX 的解决方案是可以接受的。我只是好奇是否可以不使用正则表达式(很高兴拥有并且仅适用于将来可能对此感兴趣的其他人)。
【问题讨论】:
-
您是否尝试过使用
re.findall? -
也许
re.findall(fr'\b{to_be_found}\b', text)并取len的结果? -
我的评论是关于第一句话
"he is going to school. abc is going to school."。您需要精确匹配to_be_found而不仅仅是子字符串匹配,但您希望将.视为可选。将字符串拆分为单词会将.视为shool.的一部分,并且在使用school完成时不会考虑完全匹配。一种处理方法是删除字符串中的所有特殊字符。但是在没有正则表达式的情况下这样做将需要对整个字符串进行迭代(一次一个字符)。然后你可以在<space> to_be_found<space>上str.count()。 -
如果您可以使用
re.findall()实现它,这一切都不值得。关于您的最后一条评论,您需要将正则表达式中的.替换为\.,即school\.,因为单个.在正则表达式中具有特殊含义 -
有可能,但不是最优的
标签: python regex string text nlp