python - 试图将我的 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))
解决方案
这应该是您正在寻找的。为方便起见添加了一些功能,并展示了如何在创建文件后查看文件
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)
推荐阅读
- typescript - Webpack istanbul-instrumenter-loader 不加载所有源文件
- javascript - 在 typecirpt 中,有没有办法检查由 typecirpt 加载的 wasm 中值的类型,例如:i32?
- java - Spring for Apache Kafka:具有异步请求、批处理和 Max In-flight 1 的 KafkaTemplate 行为
- select - DB2 SELECT 对两列求和并处理空值
- git - git clone 是否可以自动启用其他遥控器?
- php - 在php中从数组中获取数据
- filesystems - exFAT 簇分配策略
- java - Spring Boot 2 Set-Cookie 响应标头丢失
- microsoft-dynamics - 如何通过检查页面 DOM / HTML 来检测 CRM 当前用户名?
- python - 使用 smtplib 通过电子邮件将字典列表以缩进格式作为字符串发送?