python - 从列表中计算字符串中元素的出现次数?

标签 python string for-loop text

我正在尝试计算我收集的一些演讲中出现的语言收缩的次数。一个特定的演讲看起来像这样:

speech = "I've changed the path of the economy, and I've increased jobs in our own
home state. We're headed in the right direction - you've all been a great help."

因此,在这种情况下,我想数四 (4) 次宫缩。我有一个缩写列表,这里是前几个术语中的一些:

contractions = {"ain't": "am not; are not; is not; has not; have not",
"aren't": "are not; am not",
"can't": "cannot",...}

我的代码看起来像这样,首先是:

count = 0
for word in speech:
    if word in contractions:
        count = count + 1
print count

然而,我对此一无所获,因为代码会遍历每个字母,而不是整个单词。

最佳答案

使用str.split()在空格上拆分字符串:

for word in speech.split():

这将在任意空格上拆分;这意味着空格、制表符、换行符和一些更奇特的空白字符,以及任意数量的连续字符。

您可能需要使用 str.lower() 将您的单词小写 (否则 Ain't 将不会被发现,例如),并去除标点符号:

from string import punctuation

count = 0
for word in speech.lower().split():
    word = word.strip(punctuation)
    if word in contractions:
        count += 1

我使用 str.strip() method这里;它删除了在 string.punctuation string 中找到的所有内容从单词的开头和结尾。

关于python - 从列表中计算字符串中元素的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32979011/

相关文章:

python - 使用 brew 安装 Pyqt4

python - 如何在 Python 中找到两次之间的差异?

python - 获取当前 url 并显示在我自己的 HTML 页面上

php - jQuery 或 php 在单个节点内查找多个 html 字符串并用 span 括起来

java - 检查两个字符串是否与字母、数字和特殊字符匹配

将 2D 数组转换为 1D

python - 如何从剪贴板粘贴到 Python 窗口?

string - Delphi Embarcadero XE:使用String和PAnsiChar发出大量警告

javascript - ExtJS 循环模板

C# 为什么 List.Remove() 中断 'for loop' ?