首页 > 解决方案 > 试图将我的 dict 代码保存到 .csv 文件

问题描述

我正在尝试将此 dict 代码保存到 .csv 文件中,其中一列用于键,一列用于计数的频率。但是当我尝试运行下面的代码时,我在第 6 行的末尾收到一个错误。我做错了什么?

encryptedA_edited = abcfreq(encryptedA) 

import csv
with open("EncryptA_Edited.csv", "w", newline="") as ECA:
    writer = csv.writer(ECA)
    writer.writerows(encryptedA_edited.items())


'NoneType' object has no attribute 'items'

这是我的功能:

import string 


encryptedA = open("encryptedA.txt")
encryptedA = encryptedA.read()
encryptedB = open("encryptedB.txt")
encryptedB = encryptedB.read()
 

def abcfreq(lettervalues):
    lettervalues = lettervalues.lower().strip()
    freq = {}
    j =0

    for x in string.ascii_lowercase:
        freq[x] = 0
    
    for j in lettervalues:

        if j in freq:
            freq[j] += 1

    for key, value in (freq.items()):
         print("%s:%d" % (key, value))
    
    max_value = max(freq.values())


    max_key = max(freq, key =freq.get)
    print("The letter with the highest frequency is " + max_key +":"+str(max_value))

标签: python

解决方案


这应该是您正在寻找的。为方便起见添加了一些功能,并展示了如何在创建文件后查看文件

from random import choice, randint
import csv, os, string

def freq(element,iterable) -> int:
    return sum(1 for i in iterable if i==element)

def sample(sequence,length):
    '''
    Just for "generating" test strings
    breaks if the sequence does not have a __len__ attribute
    '''
    for i in range(length):
        yield choice(sequence)

def ascii(omissions:str='',include:bool=False) -> str:
    """
    A convenient ascii character set
        Return an ascii character set excluding the given omissions:
            "p" ->  ' ' + punctuation
            "u" ->  uppercase
            "l" ->  lowercase
            "d" ->  digits
    Feel free to omit combinations:
        >>> ascii('lup')
        ...     0123456789
    or include them
        >>> ascii('d',True)
        ...     0123456789
    """
    d = {
        "p":" "+string.punctuation,
        "u":string.ascii_uppercase,
        "l":string.ascii_lowercase,
        "d":string.digits,
    }
    return "".join(d[k] for k in d if k in omissions) if include else "".join(d[k] for k in d if not k in omissions)

def weights(string,omissions='',include=False):
    # return {i:freq(i,string) for i in set(string)} ## if you only want to measure elements of the string
    return {i:freq(i,string) for i in ascii(omissions,include)}

heaviest = lambda string: max(string,key=weights(string).get)

if __name__ == '__main__':
    s = 'abcda'
    print(s,heaviest(s),sep='\n\t') # 'a'

    strings = [''.join(sample(ascii('l',True)[:4],randint(3,5))) for i in range(4)]
        
        

    for s in strings:
        path = s+'.csv'
        with open(path, "w", newline="") as ECA:
            writer = csv.writer(ECA)
            writer.writerows(weights(s,'l',True).items())
        os.startfile(path)

推荐阅读