【问题标题】:Counting Avg Number of Words Per Sentence计算每个句子的平均单词数
【发布时间】:2017-02-09 18:17:02
【问题描述】:

我在计算每个句子的单词数时遇到了一些麻烦。就我而言,我假设句子只以"!""?""." 结尾

我有一个如下所示的列表:

["Hey, "!", "How", "are", "you", "?", "I", "would", "like", "a", "sandwich", "."]

对于上面的示例,计算结果为1 + 3 + 5 / 3。不过,我很难做到这一点!有什么想法吗?

【问题讨论】:

    标签: python math split nlp counting


    【解决方案1】:
    words = ["Hey", "!", "How", "are", "you", "?", "I", "would", "like", "a", "sandwich", "."]
    
    sentences = [[]]
    ends = set(".?!")
    for word in words:
        if word in ends: sentences.append([])
        else: sentences[-1].append(word)
    
    if sentences[0]:
        if not sentences[-1]: sentences.pop()
        print("average sentence length:", sum(len(s) for s in sentences)/len(sentences))
    

    【讨论】:

      【解决方案2】:

      一个简单的解决方案:

      mylist = ["Hey", "!", "How", "are", "you", "?", "I", "would", "like", "a", "sandwich", "."]
      terminals = set([".", "?", "!"]) # sets are efficient for "membership" tests
      terminal_count = 0
      
      for item in mylist:
          if item in terminals: # here is our membership test
              terminal_count += 1
      
      avg = (len(mylist) - terminal_count)  / float(terminal_count)
      

      这假设您只关心获得平均值,而不是每个句子的单个计数。

      如果您想花点心思,可以将 for 循环替换为以下内容:

      terminal_count = sum(1 for item in mylist if item in terminals)
      

      【讨论】:

      • 这很聪明。在循环之前将终端存储在set 中会更好一些。或者,如果您认为这太过分了,那么您至少可以将条件写成更简单的if item in ".!?"
      • @janos 很好地呼吁将终端拉出到它们自己的常量中。为了清楚起见,我更喜欢列表而不是字符串。
      • 为什么是list 为什么不是set
      • @jonas 你教育了我!我读到在找到x in y 时,集合效率更高,所以我会相应地更新。
      【解决方案3】:

      使用re.split()sum() 函数的简短解决方案:

      import re
      s = "Hey ! How are you ? I would like a sandwich ."
      parts = [len(l.split()) for l in re.split(r'[?!.]', s) if l.strip()]
      
      print(sum(parts)/len(parts))
      

      输出:

      3.0
      

      如果只能输入单词列表:

      import re
      s = ["Hey", "!", "How", "are", "you", "?", "I", "would", "like", "a", "sandwich", "."]
      parts = [len(l.split()) for l in re.split(r'[?!.]', ' '.join(s)) if l.strip()]
      
      print(sum(parts)/len(parts))   # 3.0
      

      【讨论】:

      • 第二个效果很好!我喜欢使用正则表达式,因为我正在从事某种 NLP 项目。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 2015-01-03
      相关资源
      最近更新 更多