python - 如何不计算单词之间的标点符号
问题描述
什么是计算变量的最佳方法,比如只用“不应该”等词计算撇号。
例如,“我不应该那样做”算一次,但“‘我不会那样做’”算零
基本上我如何使用计数来计算单词中的撇号而不是引号。
我没能成功地尝试很多。我只能使用基本的 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
不w[0]
以标点符号开头 ( )p
- 单词
w
不w[-1]
以标点符号结尾 ( )p
一种更 Pythonic 的方法是使用 str 可用方法,endswith
并且startswith
:
...
if p in w and not w.startswith(p) and not w.endswith(p):
...
推荐阅读
- javascript - 开玩笑 getByText 随机忽略一些文本内容
- reactjs - 等待多个元素被移除 React 测试库
- javascript - 执行 mochawesome-merge 时出现“JSON 输入意外结束”
- nuxt.js - 在 nuxt 项目中使用轻量级图表包的最佳方法?
- mysql - ERROR 1005 (HY000): Can't create table (errno: 150 "Foreign key constraint is misformed')
- amazon-web-services - AWS CloudFormation:如何处理手动删除的资源
- angular - Jasmine SpyObj 函数未定义
- angular - 从下拉列表中过滤数据并在另一个组件中显示相关数据
- css - 使整个区域可点击
- javascript - 如何避免在 JavaScript 中解构未定义的值?