gpt4 book ai didi

python - 迭代字符串以获得频率

转载 作者:行者123 更新时间:2023-11-30 23:12:45 26 4
gpt4 key购买 nike

我需要迭代通过将 10 个随机字符串写入文本文件而建立的字符串,然后读回它们并查找每个字符串中每个字母的频率。我已经完成了读回文件的操作,但我不知道如何找到字符的值。有什么帮助吗?

import string
import random
from collections import Counter

print "******************************"

print "********* EXERCISE 5 *********"

print "******************************"

print "\n**** BEGIN RANDOM STRING *****\n"


def random_string_generator():
size = random.randint(20, 80)
return "".join(random.choice(string.ascii_lowercase + string.ascii_uppercase)
for _ in range(size))

def main():
with open("exercise_five.dat", "w+") as f:
for x in range(0, 10):
data = random_string_generator()
f.write(data + "\n")
f.close()
with open("exercise_five.dat", 'r') as f:
count = 0
c = Counter()
for i in f:
print i
print "Count: %i" % count

if __name__ == '__main__': main()
print "*******************************"

最终输出应如下所示:

***** BEGIN RANDOM STRING *****
xGYMSlMHGQAMNrSzXWqphkGntMpyjMoHyRDzaNOcmVtoeAZzcV
A ==> 2 D ==> 1 G ==> 3 H ==> 2 M ==> 5 O ==> 1 N ==> 2 Q ==> 1 S ==> 2
R ==> 1 W ==> 1 V ==> 2 Y ==> 1 X ==> 1 Z ==> 1 a ==> 1 c ==> 2 e ==> 1
h ==> 1 k ==> 1 j ==> 1 m ==> 1 l ==> 1 o ==> 2 n ==> 1 q ==> 1 p ==> 2
r ==> 1 t ==> 2 y ==> 2 x ==> 1 z ==> 3
*******************************

我的代码输出现在看起来像这样:

**** BEGIN RANDOM STRING *****

QheDRPpVwDnfYWYMJQwEedJsjApRVafvMYUYuepYSerkoMgCTnHLSHwCitBr

zOFvifcwkrwXLxTrodqkxNxWVHdHDJZbYlcYjAUKz

DRgFXVkbtwpRfXPjzJmXYW

mpkVgUyvHEHAKUWpMZBYIKenicfdcBhxlqCZHFgxoFEmJjtrPykCzvQnFkTHfVthII

zEXLmudQVlpVQYexAvGFTBeUuZvqTO

KSRcpBlfNwcMoNViHFhS

QhTiBLuGCsClezAiVFYODiJXAQCQjwnBnHjWqlsZlljA

iYHznFLFeKwLtynubHTRtGGwjACdGlCpZSQcqnTSWVmufpHQRkwWYiajarnqNuzUzSC

NWlGeJFFcYwacXuUHWqmzSJmsrnWRvpmdSesXXmECuvAMkxGYpHv

WVAAiDgGaGnovCbbdazNGmWXARgdSfqCSztsNTPBdLumIXiDh

*******************************

最佳答案

从您定义 Counter 的位置开始,您可以初始化Counter从文件中读取的每一行。这会给你一个Counter具有键和值的实例,类似于字典:

with open("exercise_five.dat", 'r') as f:
for line in f:
c = Counter(line)
print(' '.join('{} ==> {}'.format(key, val) for key, val in c.items()))

对最后一行的更深入的解释:

>>> c = Counter("text")  # initialize a Counter object with the string "text"
>>> c.keys() # this instance has `keys` and `values`, similar to a dictionary
dict_keys(['e', 't', 'x'])
>>> c.items() # you can access both keys and values at the same time with `items`
dict_items([('e', 1), ('t', 2), ('x', 1)])
>>> c
Counter({'t': 2, 'e': 1, 'x': 1})
>>> for key, val in c.items():
... print(key, val)
...
e 1
t 2
x 1

此时,您只需要使用一些字符串格式即可获得您想要的输出格式,这就是 print(' '.join(...) 的内容。构造确实如此。

关于python - 迭代字符串以获得频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29687133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com