2018-10-24:統(tǒng)計(jì)字符串中各個(gè)字母/單詞的個(gè)數(shù)

b.txt文件中內(nèi)容: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() # 讀取文件,為一個(gè)字符串
str = []
outstr = {}
for x in line:
if x.isalpha():# 判斷是否為字母,
if x in outstr:# 判斷這個(gè)字母是否添加到字典
outstr[x] += 1# 添加到字典了,則值加一
else:
outstr[x] = 1 #若沒有在字典,則追加一個(gè)鍵值對到字典
print(outstr)

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

初稿如下:

file = 'b.txt'

with open(file) as f:
line = f.read() # 讀取文件,為一個(gè)字符串
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):
'''是將數(shù)量+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)

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容