计算变量(例如撇号)的最佳方法是什么?仅使用“不应该”等单词进行计数。
例如“我不应该那样做”算一次 但是“‘我不会那样做’”计数为零
基本上,我如何使用计数来计算单词中的撇号而不是引号。
我没能成功地尝试太多。我只能使用基本的 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
对于给定的单词列表,它应该只计算单词而不是单词周围。 所以“不应该”算数,但“应该”不算。
最佳答案
您可以检查它是否在单词内部:
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
- 单词
w
不是以标点符号p
开头 (w[0]
) - 单词
w
不以标点符号p
结尾 (w[-1]
)
执行此操作的更 Pythonic 方法是使用 str 可用方法,endswith
和 startswith
:
...
if p in w and not w.startswith(p) and not w.endswith(p):
...
关于python - 如何不计算单词之间的标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55758759/