python實現文件中計算字串出現的次數和字母出現的次數
from collections import counter
import string
import sys
punctuations = string.punctuation + string.whitespace #標點符號和空格(換行,製表符等)
#計算字串中子串的出現次數
def countwords(file):
with open(file,'r') as f:
lines = f.readlines()
words_list=
for line in lines:
words = line.split()
words = [word.strip(punctuations).lower() for word in words] #去除掉單詞開頭或結尾的標點符號及空格,換行等
words_list.extend(words)
counter_dict = counter(words_list) #返回乙個字典,鍵為單詞,值為出現次數
return counter_dict
#計算字串中字元的出現次數
def countword(file):
with open(file,'r') as f:
lines = f.readlines()
d=dict()
for line in lines:
str = line.strip(punctuations)
for everychar in str:
d[everychar]=d.get(everychar,0)+1
return d
if __name__ =='__main__':
print(sys.ar**[0])
counter_dict = countword('python.txt')
for key,value in counter_dict.items():
var = "%s : %s" % (key, value)
print(var)
print("\n")
counter_dict2 = countwords('python.txt')
for key,value in counter_dict2.items():
var = "%s : %s" % (key, value)
print(var)
從程式中學python
先看 import random import string chars string.ascii letters string.digits 26個字母的大小寫和數字組合 def generatecode count,length for x in range count code for y i...
Python2 爬蟲 單詞查詢程式
參考傳送門 本程式參考自上面github連線 該程式功能是輸入乙個單詞可以給出這個單詞的意思,用的是有道查詢單詞 思路是運用python的urllib庫和re正則庫 python2 如下 usr bin python coding utf 8 import urllib import sys imp...
網路爬蟲 從python2到python3
很久以前,python2的時候,簡單的弄過一點爬蟲程式,後來,到3之後,發現之前的好多程式都特麼不能用了,最最基本的抓頁面都不行了,就重新寫了乙個。python2縮寫版,大概是這樣的,忘記了沒驗證 import urllib2 response urllib2.urlopen html respon...