【问题标题】:To print the count of occurrences of a word ending with "on" in python在python中打印以“on”结尾的单词的出现次数
【发布时间】:2018-11-24 04:51:48
【问题描述】:
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

即使在删除这个词之后也是如此。 为什么会重复?

编辑:我不能使用任何模块。只有逻辑。

【问题讨论】:

  • 使用字典存储字符串及其计数,不要删除循环内的项目。
  • 它是“重复的”,因为您每次在迭代时看到这个词时都会计算gameon(即两次 - 第一次有 2 个,第二次将它们全部替换为空字符串,所以字符串中有0,但列表当然不受影响)
  • 你应该使用正则表达式!!此外,字符串是不可变的。您不能循环遍历一个并在执行此操作时对其进行修改。 string = string.replace(word,'') 只是改变了局部变量 string 是什么,它不会改变 my_string 本身...也不会改变你使用 for word in string.split() 迭代的值,这是一个(拆分)副本字符串本身。
  • 非常感谢你们! :D

标签: python string counting


【解决方案1】:

计数时无需修改字符串。

相反,您可以将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})

【讨论】:

  • 他们没有修改他们迭代的集合(一个列表)他们正在修改字符串,这当然会影响结果计数
  • @Chris_Rands,公平点,更新了更合理的建议。
  • 修改不可变字符串和修改你正在迭代的序列......非常可疑。
【解决方案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])

你可以使用字典来达到同样的效果。

【讨论】:

  • 但是我得到了 Python: 1
  • 第一个 Python 以 . 结尾,因此不会被计算在内。
【解决方案3】:

使用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)

【讨论】:

  • 为什么 Python 出现两次时只给它一次。
  • 因为其中一个'python'以.结尾 --> Python.
【解决方案4】:

你可以用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2014-08-15
    • 2012-02-03
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    相关资源
    最近更新 更多