Python:如何在文本中找到n-gram模式?
我有一个可以任意长的字符串Python:如何在文本中找到n-gram模式?,python,regex,nltk,Python,Regex,Nltk,我有一个可以任意长的字符串 s = 'Choose from millions of possibilities on Shaadi.com. Create your profile, search&contact; your special one.RegisterFree\xa0\xa0\xa0unsubscribing reply to this mail\xa0\n and 09times and this is limited time offer! and this is F
s = 'Choose from millions of possibilities on Shaadi.com. Create your profile, search&contact; your special one.RegisterFree\xa0\xa0\xa0unsubscribing reply to this mail\xa0\n and 09times and this is limited time offer! and this is For free so you are saving cash'
我有一个垃圾词列表,可能是
p_words = ['cash', 'for free', 'limited time offer']
我只想知道输入文本中是否存在模式,以及有多少次
当它只有一个词时就变得简单了
import re
p = re.compile(''.join[p_words]) # correct me if I am wrong here
m = p.match(s)
但它可以是双克、三克或n克
我们如何处理这个问题
p = re.compile('|'.join(re.escape(w) for w in p_words))
p
将匹配p_单词中的任何字符串
正则表达式使用“|”分隔符。将每种情况下的空格替换为类似“\W+”,它与非字母匹配,我认为您可以这样做。如果文本和字数不是很大,您可以从以下开始:
您可以将其性能与以下各项进行比较:
import re
from collections import Counter
p = re.compile('|'.join(map(re.escape, p_words)))
d = Counter(p.findall(s))
# -> Counter({'limited time offer': 2, 'cash': 2})
请将其速度与fgrep
进行比较,以供参考。它应该能够快速匹配输入流中的多个字符串:
$ grep -F -o -f patternlist.txt largetextfile.txt | sort | uniq -c
输出
没有理由不这样做。@J.F.Sebastian如果对结果正则表达式使用
re.finditer
或re.findall
。@Amber:re.find*
枚举匹配项,但它们本身仍然不回答“多少次”@J.F.Sebastian-鉴于OP在不针对ngrams的情况下已经在使用正则表达式来解决问题,因此假设他们能够根据需要实现计数部分似乎是合乎逻辑的。如果您需要不区分大小写的关键字搜索,请参阅谢谢@J.F.Sebastian告诉我存在计数器,我不知道it@daydreamer:注意:如果使用此算法,计数器不是最快的:
$ grep -F -o -f patternlist.txt largetextfile.txt | sort | uniq -c
2 cash
2 limited time offer