首页 > 解决方案 > 如何不计算单词之间的标点符号

问题描述

什么是计算变量的最佳方法,比如只用“不应该”等词计算撇号。

例如,“我不应该那样做”算一次,但“‘我不会那样做’”算零

基本上我如何使用计数来计算单词中的撇号而不是引号。

我没能成功地尝试很多。我只能使用基本的 for 循环来计算每个撇号,但不能具体缩小范围。

for sentence in split_sentences: 
        for w in sentence:
            for p in punctuation:
                if p == w:
                    if word in counts:
                        counts[p] += 1 
                    else:
                        counts[p] = 1

                else:
                    pass

对于给定的单词列表,它应该只计算单词而不是单词。所以“不应该”会计数,但“应该”不会。

标签: pythonpython-3.x

解决方案


您可以检查它是否单词内:

for sentence in split_sentences: 
        for w in sentence:
            for p in punctuation:
                if p in w and w[0] != p and w[-1] != p:
                    if word in counts:
                        counts[p] += 1 
                    else:
                        counts[p] = 1
                else:
                    pass

重要的一行是if p in w and w[0] != p and w[-1] != p: 我们有 3 条规则来计算:

  • 标点p在单词中2
  • 单词ww[0]以标点符号开头 ( )p
  • 单词ww[-1]以标点符号结尾 ( )p

一种更 Pythonic 的方法是使用 str 可用方法,endswith并且startswith

...
if p in w and not w.startswith(p) and not w.endswith(p):
   ...

推荐阅读