打印 python 中以 "on" 结尾的单词的出现次数

To print the count of occurrences of a word ending with "on" in python

my_string = """Strings are gameon amongst gameon the most popular data types in Python. We can create the strings by enclosing characters briton in quotes. Python treats briton single quotes the same as double quotes."""
def count_words(string):
    for word in string.split():
        if word.endswith("on") == True:
            print(word,":",string.count(word))
            string = string.replace(word,'')
count_words(my_string)

我想打印所有以 "on" 结尾的单词及其出现的单词。我收到类似

的信息
gameon : 2
gameon : 0
briton : 2
Python : 2
briton : 0

这甚至在删除这个词之后。 为什么会重复?

编辑:我无法使用任何模块。只有逻辑。

您在计数时无需修改字符串。

相反,您可以将 collections.Counter 与生成器表达式一起使用。如下所示,转换为小写并删除标点符号也是值得的。

from collections import Counter
from string import punctuation

table = str.maketrans(punctuation, ' ' * len(punctuation))
x = my_string.translate(table).lower()

c = Counter(i for i in x.split() if i.endswith('on'))

print(c)

Counter({'gameon': 2, 'python': 2, 'briton': 2})

使用collections.Counter

例如:

import collections
my_string = """Strings are gameon amongst gameon the most popular data types in Python. We can create the strings by enclosing characters briton in quotes. Python treats briton single quotes the same as double quotes."""
def count_words(string):
    for word, v in collections.Counter(string.split()).items():
        if word.endswith("on"):
            print(word,":",v)        

count_words(my_string)

输出:

('Python', ':', 1)
('briton', ':', 2)
('gameon', ':', 2)
my_string = """Strings are gameon amongst gameon the most popular data types in Python. We can create the strings by enclosing characters briton in quotes. Python treats briton single quotes the same as double quotes."""

di={}
def count_words(string):
    for word in string.split():
        if word.endswith("on") == True:
            if word in di:
                di[word]+=1
            else:
                di[word]=1
            string = string.replace(word,'')
            #print(string)
count_words(my_string)
for i in di:
    print(i,di[i])

您可以使用字典来实现相同的目的。

你可以用pandas.Seriesvalue_counts()这些词

from string import punctuation
my_string = ''.join(w for w in my_string if w not in set(punctuation))
pd.Series([i for i in my_string.split(" ") if i.endswith("on")]).value_counts()
>> (gameon, 2), (briton, 2), (Python, 2)