统计txt文件中每个单词出现的次数,返回词典,并使用类将词典转换为列表

2024-04-27 03:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我被指派去创建一个程序,读取一个txt文件,计算文本中不同单词的出现次数,并最终返回单词列表和出现次数,例如“potato”2,借助实例变量“word”和“number of occurances”的“class”,我将单词和事件存储在字典中,然后将字典转换为列表,这是因为指令告诉我,我的程序基于以下代码:

def counter (allWords):
    d = {}
    for word in allWords:
        if word in d.keys():
            d[word] = d[word] + 1
        else:
            d[word] = 1
    return d

这是我现在的代码

def counter (allWords):
    d = {}
    for word in allWords:
        if word in d.keys():
            d[word] = d[word] + 1
        else:
            d[word] = 1
    return d

infile = (input('What is the name of the file?')+'.txt')
with open(infile, encoding='utf-8') as file:
    wall_of_text = file.read()
    allWords = wall_of_text.split()

d = counter(allWords)

li = list()

def convert (d):
    for word in d.keys():
        li.append(word + " " + str(d[word]))
    return li

li = convert(d)   

你能不能帮一个新手,给我一个提示,告诉我如何在课堂上做同样的事情?你知道吗


Tags: ofin程序txtforreturndefcounter
2条回答
class Counted:
   def __init__(self,word,ct=0):       
      self.word,self.counted_occurances = word,ct
   def inc(self):
      self.counted_occurances += 1 
   def __str__(self):
      return str([self.word,self.counted_occurances])

class Counter:        
    def __init__ (self,allWords):
       d = {}
       for word in allWords:
          d.setdefault(word,Counted(word)).inc()
       self.d = d
    def __getattr__(self,attr):
       return getattr(self.d,attr)
    def __str__(self):
       return str(self.d)

def counter(allwords):
    return Counter(allwords)

c =  counter("Hello World!!")
print c

类别定义:

class Word:
    def __init__(self,word):
        self.word = word
        self.occ = 1

计数器功能:

def counter (allWords):
    d = {}
    for word in allWords:
        if word in d:
            d[word].occ += 1
        else:
            d[word] = Word(word)

return d.items()

相关问题 更多 >