自动化学习-python

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

2018-10-31  本文已影响0人  种树在此时

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)

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

上一篇下一篇

猜你喜欢

热点阅读