【问题标题】:Python: How to check if a word appears more than once in a text. (No Sets)Python:如何检查一个单词是否在文本中出现多次。 (无套装)
【发布时间】:2018-11-12 20:42:07
【问题描述】:

在我的作业中,我有一个文本,我想计算该词在文本中出现的次数。例如,假设我有一个文本文件说。

我有很多猫和狗。我有 3 只猫和 16 只狗。我喜欢狗!

因为狗这个词出现了 3 次,所以我需要输出是那个数字。但是,我将如何为随机文本执行此操作?

到目前为止,我想出了以下内容。

file = open('phrases.txt')
text = file.read()
file.close()

count  = countWords()
duplicates = 0 

for words in text:
    if words #appear twice or more 

    #if duplicates 
    duplicates+=1 

unique = count - duplicates 
#subtract the total, by the amount of duplicates.
print(unique) 

countWords() 是我制作的另一个函数,它计算文本中的总单词量**

【问题讨论】:

  • 字典`? collections.Counter?
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 On topichow to ask... the perfect question 在此处申请。特别是 5N,我们希望您在此处发布之前研究您的问题。

标签: python string python-3.x list file-io


【解决方案1】:
words = text.split()
counts = {}
for word in words:
if word not in counts:
    counts[word] = 0
counts[word] += 1

for k,v in counts.items() :
    if v==1 :
        print(k)

【讨论】:

  • 我在 count[words]+=1 处遇到 KeyError
  • 我试过我的代码它工作得很好,想法是你从文件中读取行,并使用 split() 将其存储在数组中以从行中删除空格,然后你制作一个字典并存储键中的世界和值中的计数,因此您拥有每个世界都有其计数,并且在最后一个 for 循环中,您正在打印计数 = 1 的唯一单词,请投票并选择最佳问题回答,如果您有任何问题,请联系我
【解决方案2】:
    text = "I have lots of cats and dogs. I have 3 cats and 16 dogs. I love dogs!"

    find = "dogs"
    count = 0

    for index, letter in enumerate(text):
        if letter == find[0]:
            word = text[index: index + len(find)]

            if word == find:
                count += 1

    print(count)

【讨论】:

    猜你喜欢
    • 2022-06-19
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    相关资源
    最近更新 更多