【问题标题】:Python: count the list of words except when certain words precedePython:计算单词列表,除非某些单词在前面
【发布时间】:2023-03-30 11:33:01
【问题描述】:

我不确定是否还有其他相关问题。如果是这样,请告诉我...我已经搜索过了,但我找不到任何...

如果某些单词的前面没有三个或更少的单词,我想计算单词列表。 这是来自Count occurrences of a couple of specific words的示例

我想计算单词,“foo”、“bar”、“baz”,除了“no”,在单词前面三个或更少的单词。在这种情况下,一个 bar 和 foo 不能被计算在内..

vocab = ["foo", "bar", "baz"]
exception= ["no"]
s = "foo bar baz no bar quux foo bla bla"

wordcount = dict((x,0) for x in vocab)
for w in re.findall(r"\w+", s):
    if w in wordcount:
       wordcount[w] += 1

请帮助我.. 非常感谢你提前..

【问题讨论】:

    标签: python nltk


    【解决方案1】:

    您实际上可以使用 Python 的字符串来做到这一点——不需要正则表达式:

    vocab = ["foo", "bar", "baz"]
    ex_list= ["no"]
    s = "foo bar baz no bar quux foo bla bla"
    
    words=s.split()
    wordcount = dict((x,0) for x in vocab)
    for i, word in enumerate(words):
        if i>=3 and any(w in ex_list for w in words[i-3:i]):
            continue
        elif word in vocab:    
            wordcount[word]+=1
    

    由于切片不会产生索引错误,您可以将循环简化为:

    for i, word in enumerate(words):
        if word in vocab and not any(w in ex_list for w in words[i-3:i]):
            wordcount[word]+=1
    

    【讨论】:

      【解决方案2】:

      怎么样:

      vocab = ["foo", "bar", "baz"]
      exception= ["no"]
      s = "foo bar baz no bar quux foo bla bla"
      
      wordcount = dict((x,0) for x in vocab)
      
      words = s.split()
      
      i = 0
      while i < len(words):
          cur_word = words[i]
          if cur_word in exception:
              i += 4
          else:
              if cur_word in vocab: wordcount[cur_word] += 1
              i += 1
      
      print wordcount  # {'baz': 1, 'foo': 1, 'bar': 1}
      

      只是利用了如果遇到“否”,可以跳过以下3个元素。

      【讨论】:

      • 这实际上很棒...... +1
      【解决方案3】:

      只需将no 以及以下三个单词替换为空字符串,然后计算结果字符串中的单词。

      >>> s = 'foo bar baz no bar quux foo bla bla'
      >>> vocab = ["foo", "bar", "baz"]
      >>> exception= ["no"]
      >>> wordcount = dict((x,0) for x in vocab)
      >>> m = re.sub(r'(?:^|\s)no(\s+\S+){0,3}', '', s)
      >>> for w in re.findall(r"\w+", m):
              if w in wordcount:
                  wordcount[w] += 1
      
      
      >>> wordcount
      {'foo': 1, 'bar': 1, 'baz': 1}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-30
        • 2018-11-18
        • 2015-07-12
        • 2015-06-14
        • 1970-01-01
        相关资源
        最近更新 更多