2018-10-24:统计字符串中各个字母/单词的个数

b.txt文件中内容:When you are starting the selenium server, open a console in the directory with chromedriver and selenium server and execute the above command

终稿如下:

file = 'b.txt'

with open(file) as f:
line = f.read() # 读取文件,为一个字符串
str = []
outstr = {}
for x in line:
if x.isalpha():# 判断是否为字母,
if x in outstr:# 判断这个字母是否添加到字典
outstr[x] += 1# 添加到字典了,则值加一
else:
outstr[x] = 1 #若没有在字典,则追加一个键值对到字典
print(outstr)

############################################################

初稿如下:

file = 'b.txt'

with open(file) as f:
line = f.read() # 读取文件,为一个字符串
str = []
outstr = {}
for x in line:
if x.isalpha():# 判断是否为字母,是字母再加入到str列表中去
str.append(x)

for j in range(len(str)-1,0,-1):

 #   for i in range(0,j):
for j in range(0,len(str)-1):
    if str[j] in outstr:
            #if str[i] == str[j]:
        outstr[str[j]] += 1
    else:
        outstr[str[j]] = 1
print(str)
print(outstr)

###################################################################################################################################

大神稿如下:

letters = {}

with open('b.txt') as f:
for letter in f.read():
'''判断是否是字母'''
if letter.islower():
'''判断是否存在元组中'''
if letters.get(letter):
'''是将数量+1'''
letters[letter] += 1
else:
'''第一次加入,赋值为1'''
letters[letter] = 1
print(letters)

单词版如下:

file = 'b.txt'

with open(file) as f:
line = f.read().split(' ')

outstr = {}
str = []
for x in line:
    str.append(x)
for one in line:
    a = str.count(one)
    outstr[one] = a

print(outstr)

###################################################################################################

简单粗暴版如下:

file = 'b.txt'

with open(file) as f:
line = f.read().replace(' ','')
str = []
for x in line:
str.append(x)

outstr = {}


for one in str:
    a = str.count(one)
    outstr[one] = a

print(str)
print(outstr)

##########################################

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容