python单词统计、给定一个段落()_数训营第一课笔记:Python基础知识
1.help()和dir()函數
help()函數與dir()函數都是幫助函數:
help()函數能夠提供詳細的幫助信息,dir()函數僅是簡單的羅列可用的方法。
2.基礎數據結構
基礎數據類型:數值型、布爾型和字符串型。
2.1 數值型數據有整型(int)和浮點型(float)兩種。
數值型數據的計算方法:
加 x+y
減 x-y
乘 x*y
除 x/y
冪次方 x**3
加等 x += 2 在x原有值的基礎上再加2
減等 x -= 2 在x原有值的基礎上減2
2.2 布爾型數據只有兩種類型:True 和 False
2.3 字符串類型
字符串類型用單引號或雙引號引起,引號內的內容即為字符串類型(str)。
s1 = 'hello world'
s2= "hello world"
len(s1) = 11 # 字符串計數包含空格
long_str = ' I am a teacher. '
# 去掉字符串左右兩邊的空格
long_str.strip() -> 'I am a teacher.'
# 去掉字符串左邊的空格
long_str.lstrip() -> 'I am a teacher. '
# 去掉字符串右邊的空格
long_str.rstrip() -> ' I am a teacher.'
# 將字符串中的teacher替換為student
long_str.strip().replace('teacher', 'student')
->I am a student.
num_str = '123456'
num_str.isdigit() # 判斷變量是否為數值型變量
字符串切片
str = 'hello'
# str 01234
# str -5-4-3-2-1
str[1:4] -> 'ell' # 序數從0開始,右區間為開區間
str[1:] -> 'ello'
str[:3] -> 'hel'
# 逆序數
s[-5:] -> 'hello'
s[-4:-1] -> 'ell'
格式化輸出
num_s = 100
num_t = 3
test_str = 'hello'
text = 'there are %d students in the classroom and %s' %(num_s, test_str)
text
-> 'there are 100 students in the classroom and hello'
# %d格式化輸出數字,%s格式化輸出字符串, 括號內的參數按語句中對應的順序排列。
s = 'hello world hello bigdata hello China'
s.split(' ')
-> ['hello', 'world', 'hello', 'bigdata', 'hello', 'China']
# 以空格作為分隔符將文本拆分為列表
3.判斷語句
3.1 if判斷
score = 59
if score > 90:
print 'very good.'
elif score > 85:
print 'good.'
elif socre > 70:
print 'just so so.'
else:
print 'not so good'
# if--elif--else
# 每個判斷語句寫完后記得加冒號":"
3.2 邏輯操作:與(and)或(or)非(not)
A = True
B = False
A and B = False
A or B = True
(not A) or B = False
4.容器
4.1 列表/list
string_list = ['this', 'is', 'a', 'string']
len(string_list) = 4 # len()函數計算列表中元素的個數
string_list[1:3] -> ['is', 'a'] # 列表的切片,同字符串的切片操作類似
列表中的元素沒有類型限制,不同數據類型可以添加到同一個列表中。
mass = ['this', 'is', 'good', 3.14, 10]
# 用for循環輸出list元素的數據類型
for item in mass:
print type(item)
# 用索引號index輸出個性化結果
for index in range(5)
if index % 2 == 0: # 索引號為偶數
print mass[index]
# 用while循環(注重于結束的條件)
index = 0
while index < 2:
print mass[index]
index += 1
append與extend的區別
append可將任何對象添加到list中,甚至包括list。
extend只會將list中的元素添加進去。
sort與sorted的區別
sort()函數改變列表本身的順序
sorted()函數不改變列表本身的順序
高級排序
num_list = [1, 2, 3, 4, 5, 6, 7]
print sorted(num_list, reverse = True) # 逆序排列
->[7, 6, 5, 4, 3, 2, 1]
a = ['aa', 'bbbbb', 'ccc', 'dddd']
print sorted(a, key = len) # 按字符串長度排列
->['bbbbb', 'dddd', 'ccc', 'aa']
4.2 字典/dict
字典的查找速度較列表要快很多,原因是字典采用哈希算法(hash),即一個key對應一個value,使用花括號"{}"表示。
Dict = {key1: value1, key2: value2, key3: value3}
pets = {'dogs':3, 'cats':2, 'birds':4}
print pets['dogs'] # 查找鍵值時使用中括號"[]"
->3
if 'cats' in pets:
print 'I have ' + str(pets['cats']) +'cats.' # 只有字符串才能用"+"號連接,所以pets['cats']返回的值必須用str()函數轉換為字符串。
->I have 2 cats.
# for循環遍歷字典
for pet in pets:
print 'I have ' + str(pets[pet]) + pet
-> I have 3 dogs
I have 2 cats
I have 4 birds
# 只想取出key
pets.keys() # 會得到由鍵值組成的列表對象
sum(pets.keys()) # 會得到列表中所有數字的加總和
# 從字典中成對取出數據
for (pet, num) in pets.items(): # 字典中的每一個元素都是一對鍵值對。
print pet, '=' , num
->dogs = 3
cats = 2
birds = 4
# 字典添加新的鍵值對
pets['ducks'] = 5
# 字典刪除鍵值對
del pets['ducks']
4.3 文件的讀寫
in_file = 'shanghai.txt'
for line in open(in_file):
print line.strip().splite(" ")
# 使用"for line in open(file):"這種方式打開的文件不需要關閉句柄。
# strip()函數去除了每個段落前后的空格
# splite(" ")函數將每個段落中的單詞以空格作為分隔符拆分為單個的列表元素。
#最后的拆分結果,每個段落組成一個列表,每個段落中的單詞成為對應列表中的一個元素
4.4 統計文件中每個單詞出現的頻次
# 選用字典作為容器
words_count = {} # 創建一個空字典
for line in open('shanghai.txt'):
words = line.strip().splite(" ") # 對文本做處理,去掉段落前后的空格,并以空格作為分隔符拆分段落中的單詞,構建列表。
for word in words:
if word in words_count:
words_count[word] += 1 # 如果字典中存在該單詞,對應的值+1
else:
words_count[word] = 1 # 如果字典中不存在該單詞,在字典中添加一對新的鍵值對。
#字典里存儲的是詞和詞頻
for word in words_count:
print word, words_count[word] # 使用for循環遍歷并輸出字典中的單詞和詞頻
4.5 定義函數
定義函數要用下面的形式:
def 函數名(函數參數):
函數內容
例如:
def add_num(x,y):
return x+y
add_num(3, 4)
->7
def my_func(list_x):
new_list = []
for item in list_x:
new_list.append(item**3)
return new_list
my_test = [1, 2, 3, 4, 5]
my_func(my_test)
->[1, 8, 27, 64, 125]
# 定義函數自動讀取文件并輸出文件中的單詞和詞頻
def count_words(in_file, out_file):
words_count = {}
# 對每一行去前后兩端的空格,用單詞間的空格作為分隔符分拆單詞,采用字典記錄
for line in open(in_file):
for word in line.strip().rstrip('.').splite(" "):
if word in words_count:
words_count[word] += 1
else:
words_count[word] = 1
# 打開文件并寫入結果
out = open(out_file, 'w') # 'w' 代表 'w'riting,這種打開文件的方式最后需要關閉句柄。
for word in words_count:
out.write(word + "#" + str(words_count[word]) + "\n") # 將單詞和詞頻用一定的格式寫入文件
out.close # 關閉句柄
# 調用函數
count_words('shanghai.txt', 'words_count.txt')
4.6 list comprehension
當需要對于列表中的每一個元素做相同的操作時,可以采用list comprehension方法。
[需要對item做的操作 for item in list (可選部分:對item的限制條件)]
test_list = [1, 2, 3, 4]
[item**3 for item in test_list]
->[1, 8, 27, 64]
['num_' + str(item) for item in test_list]
->['num_1', 'num_2', 'num_3', 'num_4']
[item**3 for item in test_list if item % 2 == 0] # 對列表中為偶數的元素做立方處理,并輸出新的列表
->[8, 64]
[item**4 for item in test_list if item % 2 == 0 and item > 3] # 對列表中為偶數且大于3的元素乘4次方,并輸出新的列表。
->[256]
總結
以上是生活随笔為你收集整理的python单词统计、给定一个段落()_数训营第一课笔记:Python基础知识的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql数据库二级233_MySQL数
- 下一篇: mysql 57授权失败_MYSQL教程