【问题标题】:Python, How do you check how many times an item appears in an arrayPython,如何检查一个项目在数组中出现的次数
【发布时间】:2016-05-21 12:16:51
【问题描述】:

我正在编写一个程序,它可以查找文本块中的每个单词并输出每个单词以及该单词被使用的次数。

我当前的代码在这里:

text = input("Please enter some text ")
terminator = len(text)
    n = 0
    word = ""
    wordlist = []
    while len(text) > 0:
        if word != "":
            wordlist.append(word)
        text = text[n:]
        word = ""
        n = 0
        for char in text:
            if char != " ":
                word = word + char
                n = n + 1
            else:
                text = text[1:]
                break
    for item in wordlist:
        print(item)

谢谢:)

【问题讨论】:

  • 看起来像是 collections.Counter 的工作。 . .

标签: python arrays text char words


【解决方案1】:

我会这样做:

import re
from collections import Counter

text = input("Please enter some text ")
text = re.sub(' +', ' ', text)
text = text.split(' ')
counter = Counter(text)

text = re.sub(' +', ' ', text) 行处理用户输入多个连续空格的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    相关资源
    最近更新 更多