Skip to main content
 首页 » 编程设计

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

2025年05月04日24softidea

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

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 中找到的所有内容从单词的开头和结尾。