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

bla*_*ite 1 python string text for-loop

我试图在我收集的一些演讲中计算出口头收缩的次数.一个特定的演讲看起来像这样:

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."
Run Code Online (Sandbox Code Playgroud)

所以,在这种情况下,我想计算四(4)次收缩.我有一个收缩列表,这里有一些前几个术语:

contractions = {"ain't": "am not; are not; is not; has not; have not",
"aren't": "are not; am not",
"can't": "cannot",...}
Run Code Online (Sandbox Code Playgroud)

我的代码看起来像这样,开始于:

count = 0
for word in speech:
    if word in contractions:
        count = count + 1
print count
Run Code Online (Sandbox Code Playgroud)

然而,我没有得到这个,因为代码迭代每一个字母,而不是整个单词.

Mar*_*ers 5

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

for word in speech.split():
Run Code Online (Sandbox Code Playgroud)

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

您可能需要小写使用你的话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
Run Code Online (Sandbox Code Playgroud)

我在这里使用这个str.strip()方法 ; 它会从单词的开头和结尾删除string.punctuation字符串中的所有内容.