From b0487d26e4d0f29816d852cb20a289511dee7e05 Mon Sep 17 00:00:00 2001 From: Gong Rong Ting <53923246+rtgong@users.noreply.github.com> Date: Thu, 22 Aug 2019 20:58:50 +0800 Subject: [PATCH 01/14] =?UTF-8?q?=E5=88=9B=E5=BB=BA=E4=BA=86=E4=B8=A4?= =?UTF-8?q?=E4=B8=AA=E6=96=87=E4=BB=B6=E5=A4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 创建了两个文件夹 --- exercises/1901100351/1001S02E01_helloworld.txt.txt | 1 + exercises/1901100351/README.md.txt | 0 2 files changed, 1 insertion(+) create mode 100644 exercises/1901100351/1001S02E01_helloworld.txt.txt create mode 100644 exercises/1901100351/README.md.txt diff --git a/exercises/1901100351/1001S02E01_helloworld.txt.txt b/exercises/1901100351/1001S02E01_helloworld.txt.txt new file mode 100644 index 000000000..6e229a00a --- /dev/null +++ b/exercises/1901100351/1001S02E01_helloworld.txt.txt @@ -0,0 +1 @@ +DAY 01 diff --git a/exercises/1901100351/README.md.txt b/exercises/1901100351/README.md.txt new file mode 100644 index 000000000..e69de29bb From d2b32b0744ad2c8ffd0aba0cd9a73d870608e58f Mon Sep 17 00:00:00 2001 From: Gong Rong Ting <53923246+rtgong@users.noreply.github.com> Date: Fri, 23 Aug 2019 19:46:18 +0800 Subject: [PATCH 02/14] Day 02 print 'hello world' --- .../{1001S02E01_helloworld.txt.txt => 1001S02E01_helloworld.txt} | 0 exercises/1901100351/1001S02E02_hello_python.py | 1 + 2 files changed, 1 insertion(+) rename exercises/1901100351/{1001S02E01_helloworld.txt.txt => 1001S02E01_helloworld.txt} (100%) create mode 100644 exercises/1901100351/1001S02E02_hello_python.py diff --git a/exercises/1901100351/1001S02E01_helloworld.txt.txt b/exercises/1901100351/1001S02E01_helloworld.txt similarity index 100% rename from exercises/1901100351/1001S02E01_helloworld.txt.txt rename to exercises/1901100351/1001S02E01_helloworld.txt diff --git a/exercises/1901100351/1001S02E02_hello_python.py b/exercises/1901100351/1001S02E02_hello_python.py new file mode 100644 index 000000000..0ab9637cd --- /dev/null +++ b/exercises/1901100351/1001S02E02_hello_python.py @@ -0,0 +1 @@ +print('hello world!') From 91b7f1bbfba53167a234846d29211cfe18311e9d Mon Sep 17 00:00:00 2001 From: Gong Rong Ting <53923246+rtgong@users.noreply.github.com> Date: Fri, 23 Aug 2019 19:53:13 +0800 Subject: [PATCH 03/14] Day 02 print 'hello world' --- exercises/1901100351/1001S02E02_hello_python.py | 1 - exercises/1901100351/1001S02E_hello_python.py | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) delete mode 100644 exercises/1901100351/1001S02E02_hello_python.py create mode 100644 exercises/1901100351/1001S02E_hello_python.py diff --git a/exercises/1901100351/1001S02E02_hello_python.py b/exercises/1901100351/1001S02E02_hello_python.py deleted file mode 100644 index 0ab9637cd..000000000 --- a/exercises/1901100351/1001S02E02_hello_python.py +++ /dev/null @@ -1 +0,0 @@ -print('hello world!') diff --git a/exercises/1901100351/1001S02E_hello_python.py b/exercises/1901100351/1001S02E_hello_python.py new file mode 100644 index 000000000..7ddfc8f85 --- /dev/null +++ b/exercises/1901100351/1001S02E_hello_python.py @@ -0,0 +1 @@ +print('hello world!') \ No newline at end of file From 1eac2174d602cfc2f70a89c14b2b0e3702466ce1 Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Sun, 25 Aug 2019 16:35:44 +0800 Subject: [PATCH 04/14] =?UTF-8?q?1901100351=E3=80=90=E8=87=AA=E5=AD=A6?= =?UTF-8?q?=E8=AE=AD=E7=BB=83=E8=90=A520=E3=80=91day03?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I had wrot two calculators with python language. --- exercises/1901100351/1001S02E03_calculator.py | 20 ++++++++++++++++ .../1901100351/1001S02E03_calculator1.py | 23 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 exercises/1901100351/1001S02E03_calculator.py create mode 100644 exercises/1901100351/1001S02E03_calculator1.py diff --git a/exercises/1901100351/1001S02E03_calculator.py b/exercises/1901100351/1001S02E03_calculator.py new file mode 100644 index 000000000..13b0791a3 --- /dev/null +++ b/exercises/1901100351/1001S02E03_calculator.py @@ -0,0 +1,20 @@ +# This is my calculator with python language + +print('A calculator with python language') +operator = input('Please enter an operator (+, -, *, /) : ') +first_number = input('Please enter the first number : ') +second_number = input('Please enter the second number : ') + +a = int(first_number) +b = int(second_number) + +if operator == '+': + print(a, '+', b, '=', a + b) +elif operator == '-': + print(a, '-', b, '=', a - b) +elif operator == '*': + print(a, '*', b, '=', a * b) +elif operator == '/': + print(a, '/', b, '=', a / b) +else: + print('Null operator') \ No newline at end of file diff --git a/exercises/1901100351/1001S02E03_calculator1.py b/exercises/1901100351/1001S02E03_calculator1.py new file mode 100644 index 000000000..534dfabed --- /dev/null +++ b/exercises/1901100351/1001S02E03_calculator1.py @@ -0,0 +1,23 @@ +operation=input(''' +Please type in the math operation you would like to complete: ++ for addition +- for subtraction +* for multiplication +/ for division +''') +nubmber_1=float(input('Enter your first number:')) +nubmber_2=float(input('Enter your second number:')) +if operation=='+': + print('{}+{}='.format(nubmber_1,nubmber_2)) + print(nubmber_1+nubmber_2) +elif operation=='-': + print('{}-{}='.format(nubmber_1,nubmber_2)) + print(nubmber_1-nubmber_2) +elif operation=='*': + print('{}*{}='.format(nubmber_1,nubmber_2)) + print(nubmber_1*nubmber_2) +elif operation=='/': + print('{}/{}='.format(nubmber_1,nubmber_2)) + print(nubmber_1/nubmber_2) +else: + print('You have not typed a valid operator,please run the program again.') \ No newline at end of file From d228a4b27949083d645a509f147fbe2d8fb12d98 Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Mon, 26 Aug 2019 23:01:20 +0800 Subject: [PATCH 05/14] Create 1001S02E04_control_flow.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 01. 学习if、for…in、while、range等语法; 02. 尝试理解control flow --- .../1901100351/1001S02E04_control_flow.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 exercises/1901100351/1001S02E04_control_flow.py diff --git a/exercises/1901100351/1001S02E04_control_flow.py b/exercises/1901100351/1001S02E04_control_flow.py new file mode 100644 index 000000000..919c8bfd1 --- /dev/null +++ b/exercises/1901100351/1001S02E04_control_flow.py @@ -0,0 +1,27 @@ +print('九九乘法表01') +for i in range(1, 10): + for j in range(1, i+1): + print('{}x{}={}\t'.format(j, i, i*j), end='') + print() +print('\n') + + +print('九九乘法表02') +row = 1 # 行号 +while row<= 9: + col = 1 # 列号 + while col<=row: + print("%d*%d=%d" %(col,row,col*row), end='\t') + col += 1 + print('') + row += 1 +print('\n') + +print('九九乘法表(除去偶数行)') +for i in range(1,10): + if i % 2 == 0 : + i += 1 + continue + for j in range(1,i+1): + print('{}x{}={}\t'.format(i,j,i*j),end='') + print('') \ No newline at end of file From df49fecb9b80d0b240936a3abc585067022c1a80 Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Tue, 27 Aug 2019 21:36:11 +0800 Subject: [PATCH 06/14] =?UTF-8?q?=E5=AF=B9control=20flow=E7=BB=83=E4=B9=A0?= =?UTF-8?q?=E7=9A=84=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根据教学视频,对control flow练习进行了优化; --- .../1901100351/1001S02E04_control_flow.py | 42 +++++++------------ 1 file changed, 16 insertions(+), 26 deletions(-) diff --git a/exercises/1901100351/1001S02E04_control_flow.py b/exercises/1901100351/1001S02E04_control_flow.py index 919c8bfd1..bc069fd7b 100644 --- a/exercises/1901100351/1001S02E04_control_flow.py +++ b/exercises/1901100351/1001S02E04_control_flow.py @@ -1,27 +1,17 @@ -print('九九乘法表01') -for i in range(1, 10): - for j in range(1, i+1): - print('{}x{}={}\t'.format(j, i, i*j), end='') - print() -print('\n') +print('打印九九乘法表') +for i in range(1, 10):# 从第1行循环到第9行 + print('第%d行' % i, end='\t')# 打印行号 + for j in range(1, i+1):# j从1循环到i+1 + print(i,'*',j,'=',i*j,end='\t')# 打印乘法算式,并空8个字符 + # print('{}x{}={}\t'.format(j, i, i*j), end='\t') + print()# 结束打印 - -print('九九乘法表02') -row = 1 # 行号 -while row<= 9: - col = 1 # 列号 - while col<=row: - print("%d*%d=%d" %(col,row,col*row), end='\t') - col += 1 - print('') - row += 1 -print('\n') - -print('九九乘法表(除去偶数行)') -for i in range(1,10): - if i % 2 == 0 : - i += 1 - continue - for j in range(1,i+1): - print('{}x{}={}\t'.format(i,j,i*j),end='') - print('') \ No newline at end of file +print('打印去除偶数行的九九乘法表') +i = 1 +while i < 10: + if i % 2 == 0:# 如果i是奇数 + print()# 不打印 + else: + for j in range(1, i+1): + print(i,'*',j,'=',i*j,end='\t') + i += 1 From 6415f6100c3b16d8789483d070af4701b8ec5b9b Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Sat, 31 Aug 2019 20:50:05 +0800 Subject: [PATCH 07/14] =?UTF-8?q?=E7=AC=AC5=E6=AC=A1=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=EF=BC=9A=E5=AD=A6=E4=B9=A0=E6=95=B0=E6=8D=AE=E5=AE=B9=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 完成3项任务,即字符串处理,字符串中的统计,数组操作 --- exercises/1901100351/1001S02E05_array.py | 15 +++++++ exercises/1901100351/1001S02E05_stats_text.py | 41 +++++++++++++++++++ exercises/1901100351/1001S02E05_string.py | 40 ++++++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 exercises/1901100351/1001S02E05_array.py create mode 100644 exercises/1901100351/1001S02E05_stats_text.py create mode 100644 exercises/1901100351/1001S02E05_string.py diff --git a/exercises/1901100351/1001S02E05_array.py b/exercises/1901100351/1001S02E05_array.py new file mode 100644 index 000000000..1470f6719 --- /dev/null +++ b/exercises/1901100351/1001S02E05_array.py @@ -0,0 +1,15 @@ +array=[0,1,2,3,4,5,6,7,8,9] #输入数组 +string='' #初始化字符串 +array=sorted(array,reverse=True)#翻转字符串,reverse=true为降序 +print(array) + +for i in range(0,len(array)): #循环查找 + string=string+str(array[i]) #拼接字符串 +print(array) + +string=string[2:8] #切片取出元素 +string=string[::-1] #字符串翻转 +string=int(string) #将字符串转为整数 +print(string) + +print(bin(string),'\n',oct(string),'\n',hex(string)) #二进制、八进制、十六进制 分别为bin\oct\hex \ No newline at end of file diff --git a/exercises/1901100351/1001S02E05_stats_text.py b/exercises/1901100351/1001S02E05_stats_text.py new file mode 100644 index 000000000..6be7bdfb9 --- /dev/null +++ b/exercises/1901100351/1001S02E05_stats_text.py @@ -0,0 +1,41 @@ +text = ''' +the Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those! +''' + +t1=text.replace(',',' ').replace('.',' ').replace('--',' ').replace('!',' ').replace('*',' ').replace('!',' ') +# 去掉文本中的中文字符、英文字符、字号、连接符 +text=text.split() + +# 统计各个单词出现的次数 +textDict={}#创建名称为textDict的字典 +for word in text:#在text中循环查找word + wordCount=text.count(word)#在text中查找word的次数定义为wordCount + wordDict={word:wordCount}#创建wordCount字典,并定义word与word出现次数为一一对应的(键,值) + textDict.update(wordDict)#将wordDict字典的“键值”更新到textDict字典中 + +# 按照出现次数从大到小排序 +sortT1=sorted(textDict.items(),key=lambda x:x[1],reverse=True) +# sorted()表示排序,items()表示以列表返回可遍历的(键, 值) 元组数组 +# 因为字典中基本元素是(键,值),即一个元组,所以要用key=lambda排序 +# lambda是固定写法的隐函数,x:x[1]表示以元组中的第2个元素为对象,reverse=True表示按降序排列 +print(sortT1) \ No newline at end of file diff --git a/exercises/1901100351/1001S02E05_string.py b/exercises/1901100351/1001S02E05_string.py new file mode 100644 index 000000000..eed52958d --- /dev/null +++ b/exercises/1901100351/1001S02E05_string.py @@ -0,0 +1,40 @@ +text = ''' +the Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those! +''' + +t1=text.replace(',',' ').replace('.',' ').replace('--',' ').replace('!',' ').replace('*',' ').replace('!',' ') +# 去掉文本中的中文字符、英文字符、字号、连接符 +t2=t1.replace('better','worse')# 用worse替换better +print(t2) + +t3=t2.split()# 以空格为分隔符,将t2中的字符串转换为列表 +t4=[]# 将t4创建为列表,通过索引获取字符串中的字符 +for a in t3:# 在t3中循环查找a(a代表所有字符串) + if 'ea' not in a:# 如果ea不在字符串中 + t4.append(a)# 在t4后添加字符串(即把不含ea的字符串挑出来放在t4中) +print(t4) + +t5=(' '.join(t4))# 用空格做分隔t4中的字符串,形成t5 +t6=t5.swapcase()# 将t5中的大小写字母反转,形成t6 +t7=t6.split()# 以空格为分隔符,将t6中的字符串切片,形成t7 +print(sorted(t7,key=str.lower))#将t7中的字符串按字母升序排列 \ No newline at end of file From f97f2257568944caa81c610bf1dc7d1bebeee071 Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Sun, 1 Sep 2019 21:35:45 +0800 Subject: [PATCH 08/14] =?UTF-8?q?=E8=A1=A5=E5=85=85=E9=83=A8=E5=88=86?= =?UTF-8?q?=E5=91=BD=E4=BB=A4=E7=9A=84=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 复习之前学习的内容,修改若干书写,补充部分注释,相当于重读自己完成的代码 --- exercises/1901100351/1001S02E03_calculator.py | 24 +++++++++---------- .../1901100351/1001S02E03_calculator1.py | 8 +++---- .../1901100351/1001S02E04_control_flow.py | 4 ++-- exercises/1901100351/1001S02E05_array.py | 2 +- exercises/1901100351/1001S02E05_stats_text.py | 2 +- .../1901100351/{README.md.txt => README.md} | 0 6 files changed, 20 insertions(+), 20 deletions(-) rename exercises/1901100351/{README.md.txt => README.md} (100%) diff --git a/exercises/1901100351/1001S02E03_calculator.py b/exercises/1901100351/1001S02E03_calculator.py index 13b0791a3..0a215f695 100644 --- a/exercises/1901100351/1001S02E03_calculator.py +++ b/exercises/1901100351/1001S02E03_calculator.py @@ -1,20 +1,20 @@ # This is my calculator with python language print('A calculator with python language') -operator = input('Please enter an operator (+, -, *, /) : ') -first_number = input('Please enter the first number : ') -second_number = input('Please enter the second number : ') +operator=input('Please enter an operator (+, -, *, /) : ') +first_number=input('Please enter the first number : ') +second_number=input('Please enter the second number : ') -a = int(first_number) -b = int(second_number) +a=int(first_number)#定义a等于第一个数字(数值型) +b=int(second_number)#定义b等于第二个数字(数值型) -if operator == '+': - print(a, '+', b, '=', a + b) -elif operator == '-': - print(a, '-', b, '=', a - b) -elif operator == '*': +if operator=='+':#如果输入+ + print(a, '+', b, '=', a + b)#显示两个数字相加及结果 +elif operator=='-':#如果输入- + print(a, '-', b, '=', a - b)#显示两个数字相减及结果 +elif operator=='*': print(a, '*', b, '=', a * b) -elif operator == '/': +elif operator=='/': print(a, '/', b, '=', a / b) else: - print('Null operator') \ No newline at end of file + print('Null operator') #其他情况,显示无效输入 \ No newline at end of file diff --git a/exercises/1901100351/1001S02E03_calculator1.py b/exercises/1901100351/1001S02E03_calculator1.py index 534dfabed..0c20f8d06 100644 --- a/exercises/1901100351/1001S02E03_calculator1.py +++ b/exercises/1901100351/1001S02E03_calculator1.py @@ -4,11 +4,11 @@ - for subtraction * for multiplication / for division -''') -nubmber_1=float(input('Enter your first number:')) -nubmber_2=float(input('Enter your second number:')) +''')#用'''输入分段内容 +nubmber_1=float(input('Enter your first number:'))#输入第一个浮点数值 +nubmber_2=float(input('Enter your second number:'))#输入第二个浮点数值 if operation=='+': - print('{}+{}='.format(nubmber_1,nubmber_2)) + print('{}+{}='.format(nubmber_1,nubmber_2))#‘{}+{}=’.format()表示按默认顺序的格式化函数 print(nubmber_1+nubmber_2) elif operation=='-': print('{}-{}='.format(nubmber_1,nubmber_2)) diff --git a/exercises/1901100351/1001S02E04_control_flow.py b/exercises/1901100351/1001S02E04_control_flow.py index bc069fd7b..0e8e9d095 100644 --- a/exercises/1901100351/1001S02E04_control_flow.py +++ b/exercises/1901100351/1001S02E04_control_flow.py @@ -8,8 +8,8 @@ print('打印去除偶数行的九九乘法表') i = 1 -while i < 10: - if i % 2 == 0:# 如果i是奇数 +while i<10:#while是条件判断循环 + if i%2==0:# 如果i是奇数 print()# 不打印 else: for j in range(1, i+1): diff --git a/exercises/1901100351/1001S02E05_array.py b/exercises/1901100351/1001S02E05_array.py index 1470f6719..843ff0bfc 100644 --- a/exercises/1901100351/1001S02E05_array.py +++ b/exercises/1901100351/1001S02E05_array.py @@ -3,7 +3,7 @@ array=sorted(array,reverse=True)#翻转字符串,reverse=true为降序 print(array) -for i in range(0,len(array)): #循环查找 +for i in range(0,len(array)): #for…in循环查找,len()字符串长度 string=string+str(array[i]) #拼接字符串 print(array) diff --git a/exercises/1901100351/1001S02E05_stats_text.py b/exercises/1901100351/1001S02E05_stats_text.py index 6be7bdfb9..31511ce9f 100644 --- a/exercises/1901100351/1001S02E05_stats_text.py +++ b/exercises/1901100351/1001S02E05_stats_text.py @@ -24,7 +24,7 @@ t1=text.replace(',',' ').replace('.',' ').replace('--',' ').replace('!',' ').replace('*',' ').replace('!',' ') # 去掉文本中的中文字符、英文字符、字号、连接符 -text=text.split() +text=text.split() #以空格为分隔符,将text中的字符串转换为列表 # 统计各个单词出现的次数 textDict={}#创建名称为textDict的字典 diff --git a/exercises/1901100351/README.md.txt b/exercises/1901100351/README.md similarity index 100% rename from exercises/1901100351/README.md.txt rename to exercises/1901100351/README.md From d29ea78c8d65a12b2ef05fd3e522c3ac041629c2 Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Sat, 7 Sep 2019 22:17:25 +0800 Subject: [PATCH 09/14] =?UTF-8?q?=E7=AC=AC6=E6=AC=A1=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=EF=BC=8C=E5=AD=A6=E4=B9=A0=E8=87=AA=E5=AE=9A=E4=B9=89=E5=87=BD?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 学习、练习自定义函数 --- exercises/1901100351/1001S02E06_stats_word.py | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 exercises/1901100351/1001S02E06_stats_word.py diff --git a/exercises/1901100351/1001S02E06_stats_word.py b/exercises/1901100351/1001S02E06_stats_word.py new file mode 100644 index 000000000..97a1d0706 --- /dev/null +++ b/exercises/1901100351/1001S02E06_stats_word.py @@ -0,0 +1,65 @@ +text = ''' +the Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those! +''' +import re +def stats_text_en(text): #定义函数 + ''' + 这是一个统计英文词频并按出现次数降序排列的函数 + ''' + text_1 = re.sub('\W',' ',text) #不是字符的,都转换为空格,主要去除标点符号 + text_1 = text_1.lower() #转换为小写 + textlist_1 = text_1.split() #将段落转换为列表 + dict1 = {} #定义字典 + for i in textlist_1: + num= textlist_1.count(i)#统计词频 + r1 = {i:num}#定义元组 + dict1.update(r1)#更新词典 + dict2=sorted(dict1.items(),key = lambda dict_items:dict_items[1], reverse=True)#排序 + return(dict2) +print(stats_text_en(text)) + + +def stats_text_cn(text_cn):#设定函数 + ''' + 这是一个统计中文汉字字频并按出现次数降序排列的函数 + ''' + + word_dict = {} #定义一个空字典,作为结果容器 + cn_list = list(text_cn) #将文本直接拆分为列表 + for s in cn_list: #统计中文汉字个数,并将结果返回word_dict中 + if '\u4e00'<= s <= '\u9fff':#中文字符的代码区间 + count=cn_list.count(s)#统计字符出现次数 + r1={s:count}#定义字典中的元组 + word_dict.update(r1)#更新列表 + word_sorted = sorted(word_dict.items(), key=lambda items:items[1],reverse=True) + #按字频降序排列输出结果 + return word_sorted + +text_cn = ''' +人类历史纷繁芜杂,到底什么才是最重要、最核心的推力? +是精英,还是民众?是制度,还是技术?是欲望,还是道德? +很多时候,似乎是精英主导社会,但也有许多时候,民众的力量也能摧枯拉朽; +很多时候,似乎是制度塑造社会,但也有许多时候,技术的进步会带来制度的重构; +很多时候,似乎是人们的欲望推动着社会,但也有许多时候,道德的力量也能重振河山。 +''' +print(stats_text_cn(text_cn)) \ No newline at end of file From c3d3a7de37b4eadf2ce9c4c35bb17eb8bfc353a4 Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Wed, 11 Sep 2019 20:43:31 +0800 Subject: [PATCH 10/14] =?UTF-8?q?DAY7:=20=E5=AD=A6=E4=B9=A0=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在DAY6自定义函数的基础上,学习函数调用 --- exercises/1901100351/d07/mymodule/main.py | 54 ++++++++++++ .../1901100351/d07/mymodule/stats_word.py | 83 +++++++++++++++++++ 2 files changed, 137 insertions(+) create mode 100644 exercises/1901100351/d07/mymodule/main.py create mode 100644 exercises/1901100351/d07/mymodule/stats_word.py diff --git a/exercises/1901100351/d07/mymodule/main.py b/exercises/1901100351/d07/mymodule/main.py new file mode 100644 index 000000000..e15f8fd6c --- /dev/null +++ b/exercises/1901100351/d07/mymodule/main.py @@ -0,0 +1,54 @@ +import stats_word + +text = ''' +愚公移山 +太行,王屋二山的北面,住了一個九十歲的老翁,名叫愚公。二山佔地廣闊,擋住去路,使他和家人往來極為不便。 +一天,愚公召集家人說:「讓我們各盡其力,剷平二山,開條道路,直通豫州,你們認為怎樣?」 +大家都異口同聲贊成,只有他的妻子表示懷疑,並說:「你連開鑿一個小丘的力量都沒有,怎可能剷平太行、王屋二山呢?況且,鑿出的土石又丟到哪裏去呢?」 +大家都熱烈地說:「把土石丟進渤海裏。」 +於是愚公就和兒孫,一起開挖土,把土石搬運到渤海去。 +愚公的鄰居是個寡婦,有個兒子八歲也興致勃勃地走來幫忙。 +寒來暑往,他們要一年才能往返渤海一次。 +住在黃河河畔的智叟,看見他們這樣辛苦,取笑愚公說:「你不是很愚蠢嗎?你已一把年紀了,就是用盡你的氣力,也不能挖去山的一角呢?」 +愚公歎息道:「你有這樣的成見,是不會明白的。你比那寡婦的小兒子還不如呢!就算我死了,還有我的兒子,我的孫子,我的曾孫子,他們一直傳下去。 +而這二山是不會加大的,總有一天,我們會把它們剷平。」 +智叟聽了,無話可說: +二山的守護神被愚公的堅毅精神嚇倒,便把此事奏知天帝。天帝佩服愚公的精神,就命 +兩位大力神揹走二山。 + + +How The Foolish Old Man Moved Mountains +Yugong was a ninety-year-old man who lived at the north +of two high mountains, Mount Taixing and Mount Wangwu. +Stretching over a wide expanse of land, the mountains blocked +yugong’s way making it inconvenient for him and his family to get around. +One day yugong gathered his family +together and said,”Let’s do our best to level these two mountains. We shall open a road that leads to Yuzhou. What +do you think?” +All but his wife agreed with him. +“You don’t have the strength to cut even a small mound,” muttered +his wife. “How on earth do you suppose you can level Mount Taixin and Mount Wanwu? Moreover, where will all the +earth and rubble go?” +“Dump them into the Sea of Bohai!” said everyone. +So Yugong, his sons, and his grandsons +started to break up rocks and remove the earth. They transported the earth and rubble to the Sea of Bohai. +Now Yugong +’s neighbour was a widow who had an only child eight years old. Evening the young boy offered his help eagerly. +Summer went by and winter came. It took Yugong and his crew a full year to travel back and forth once. +On the bank of +the Yellow River dwelled an old man much respected for his wisdom. When he saw their back-breaking labour, he +ridiculed Yugong saying,”Aren’t you foolish, my friend? You are very old now, and with whatever remains of your +waning strength, you won’t be able to remove even a corner of the mountain.” +Yugong uttered a sigh and said,”A +biased person like you will never understand. You can’t even compare with the widow’s little boy!” +“Even if I +were dead, there will still be my children, my grandchildren, my great grandchildren, my great great grandchildren. +They descendants will go on forever. But these mountains will not grow any taler. We shall level them one day!” he +declared with confidence. +The wise old man was totally silenced. +When the guardian gods of the mountains saw how +determined Yugong and his crew were, they were struck with fear and reported the incident to the Emperor of Heavens. +Filled with admiration for Yugong, the Emperor of Heavens ordered two mighty gods to carry the mountains away. +''' + +print(stats_word.stats_text(text)) \ No newline at end of file diff --git a/exercises/1901100351/d07/mymodule/stats_word.py b/exercises/1901100351/d07/mymodule/stats_word.py new file mode 100644 index 000000000..351cb11c7 --- /dev/null +++ b/exercises/1901100351/d07/mymodule/stats_word.py @@ -0,0 +1,83 @@ +# 统计参数中英文单词出现的次数,并按降序排列 +def stats_text_en(text): #定义函数 + elements = text.split()#对字符串进行切片 + words = []#设置列表 + symbols = ',.*-!' + for element in elements: + for symbol in symbols: + element = element.replace(symbol,'') + if len(element): + words.append(element) + counter = {}#创建字典 + word_set = set(words)#创建无序不重复集合 + + for word in word_set: + counter[word] = words.count(word) + return sorted(counter.items(), key=lambda x:x[1], reverse=True) + +# 统计参数中汉字出现次数,并按降序排列 +def stats_text_cn(text):#设定函数 + cn_charactors = [] + for charactor in text: + if '\u4e00'<= charactor <= '\u9fff':#中文字符的代码区间 + cn_charactors.append(charactor) + counter = {}#创建字典 + cn_charactor_set = set(cn_charactors) + for charactor in cn_charactor_set: + counter[charactor] = cn_charactors.count(charactor) + return sorted(counter.items(),key=lambda x:x[1], reverse=True) + +# 合并英汉词频统计 +def stats_text(text_en_cn) : + return (stats_text_en(text_en_cn)+stats_text_cn(text_en_cn)) + + +en_text = ''' +the Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those! +''' + +cn_text = ''' +Python之禅 by Tim Peters + +优美胜于丑陋 +明了胜于晦涩 +简洁胜于复杂 +复杂胜于凌乱 +扁平胜于嵌套 +间隔胜于紧凑 +可读性很重要 +尽管实用会打破纯粹,也不可违背规则 +不要包容任何错误,除非你确定需要这样做 +当存在多种可能,不要尝试去猜测 +而是尽量找一种,最好是唯一一种明显的解决方案 +虽然这并不容易,因为你不是 Python 之父 +做也许好过不做,但不假思索就动手还不如不做 +如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然 +命名空间是一种绝妙的理念,请多加利用 +''' + +if __name__ == "__main__": + en_result = stats_text_en(en_text) + cn_result = stats_text_cn(cn_text) + print('统计参数中英文单词出现次数==>\n', en_result) + print('统计参数中汉字出现次数==>\n', cn_result) \ No newline at end of file From 2a90189e710ce0d662f5f2accbd6b9c2fbce53f1 Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Wed, 11 Sep 2019 20:45:59 +0800 Subject: [PATCH 11/14] =?UTF-8?q?=E6=9B=B4=E6=96=B0DAY5=E3=80=81DAY6?= =?UTF-8?q?=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 听完视频课后,对作业作了一些修改和完善 --- .../1901100351/1001S02E05_stats_text1.py | 42 ++++++++++ exercises/1901100351/1001S02E06_stats_word.py | 65 --------------- .../1901100351/1001S02E06_stats_word1.py | 79 +++++++++++++++++++ 3 files changed, 121 insertions(+), 65 deletions(-) create mode 100644 exercises/1901100351/1001S02E05_stats_text1.py delete mode 100644 exercises/1901100351/1001S02E06_stats_word.py create mode 100644 exercises/1901100351/1001S02E06_stats_word1.py diff --git a/exercises/1901100351/1001S02E05_stats_text1.py b/exercises/1901100351/1001S02E05_stats_text1.py new file mode 100644 index 000000000..6565f179c --- /dev/null +++ b/exercises/1901100351/1001S02E05_stats_text1.py @@ -0,0 +1,42 @@ +sample_text = ''' +the Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those! +''' + +elements = sample_text.split() +words = [] +symbols = ',.*-!' +for element in elements: + for symbol in symbols: + element = element.replace(symbol,'') + if len(element): + words.append(element) +print('正常的英文单词==>',words) + +counter = {} +word_set = set(words) + +for word in word_set: + counter[word] = words.count(word) +print('英文单词出现次数 ==>',counter) + +print('从大到小输出所有单词出现的次数 ==>', sorted(counter.items(), key=lambda x: x[1], reverse=True)) \ No newline at end of file diff --git a/exercises/1901100351/1001S02E06_stats_word.py b/exercises/1901100351/1001S02E06_stats_word.py deleted file mode 100644 index 97a1d0706..000000000 --- a/exercises/1901100351/1001S02E06_stats_word.py +++ /dev/null @@ -1,65 +0,0 @@ -text = ''' -the Zen of Python, by Tim Peters - -Beautiful is better than ugly. -Explicit is better than implicit. -Simple is better than complex. -Complex is better than complicated. -Flat is better than nested. -Sparse is better than dense. -Readability counts. -Special cases aren't special enough to break the rules. -Although practicality beats purity. -Errors should never pass silently. -Unless explicitly silenced. -In the face of ambiguity, refuse the temptation to guess. -There should be one-- and preferably only one --obvious way to do it. -Although that way may not be obvious at first unless you're Dutch. -Now is better than never. -Although never is often better than *right* now. -If the implementation is hard to explain, it's a bad idea. -If the implementation is easy to explain, it may be a good idea. -Namespaces are one honking great idea -- let's do more of those! -''' -import re -def stats_text_en(text): #定义函数 - ''' - 这是一个统计英文词频并按出现次数降序排列的函数 - ''' - text_1 = re.sub('\W',' ',text) #不是字符的,都转换为空格,主要去除标点符号 - text_1 = text_1.lower() #转换为小写 - textlist_1 = text_1.split() #将段落转换为列表 - dict1 = {} #定义字典 - for i in textlist_1: - num= textlist_1.count(i)#统计词频 - r1 = {i:num}#定义元组 - dict1.update(r1)#更新词典 - dict2=sorted(dict1.items(),key = lambda dict_items:dict_items[1], reverse=True)#排序 - return(dict2) -print(stats_text_en(text)) - - -def stats_text_cn(text_cn):#设定函数 - ''' - 这是一个统计中文汉字字频并按出现次数降序排列的函数 - ''' - - word_dict = {} #定义一个空字典,作为结果容器 - cn_list = list(text_cn) #将文本直接拆分为列表 - for s in cn_list: #统计中文汉字个数,并将结果返回word_dict中 - if '\u4e00'<= s <= '\u9fff':#中文字符的代码区间 - count=cn_list.count(s)#统计字符出现次数 - r1={s:count}#定义字典中的元组 - word_dict.update(r1)#更新列表 - word_sorted = sorted(word_dict.items(), key=lambda items:items[1],reverse=True) - #按字频降序排列输出结果 - return word_sorted - -text_cn = ''' -人类历史纷繁芜杂,到底什么才是最重要、最核心的推力? -是精英,还是民众?是制度,还是技术?是欲望,还是道德? -很多时候,似乎是精英主导社会,但也有许多时候,民众的力量也能摧枯拉朽; -很多时候,似乎是制度塑造社会,但也有许多时候,技术的进步会带来制度的重构; -很多时候,似乎是人们的欲望推动着社会,但也有许多时候,道德的力量也能重振河山。 -''' -print(stats_text_cn(text_cn)) \ No newline at end of file diff --git a/exercises/1901100351/1001S02E06_stats_word1.py b/exercises/1901100351/1001S02E06_stats_word1.py new file mode 100644 index 000000000..26e1c8326 --- /dev/null +++ b/exercises/1901100351/1001S02E06_stats_word1.py @@ -0,0 +1,79 @@ +# 统计参数中英文单词出现的次数,并按降序排列 +def stats_text_en(text): #定义函数 + elements = text.split()#对字符串进行切片 + words = []#设置列表 + symbols = ',.*-!' + for element in elements: + for symbol in symbols: + element = element.replace(symbol,'') + if len(element): + words.append(element) + counter = {}#创建字典 + word_set = set(words)#创建无序不重复集合 + + for word in word_set: + counter[word] = words.count(word) + return sorted(counter.items(), key=lambda x:x[1], reverse=True) + +# 统计参数中汉字出现次数,并按降序排列 +def stats_text_cn(text):#设定函数 + cn_charactors = [] + for charactor in text: + if '\u4e00'<= charactor <= '\u9fff':#中文字符的代码区间 + cn_charactors.append(charactor) + counter = {}#创建字典 + cn_charactor_set = set(cn_charactors) + for charactor in cn_charactor_set: + counter[charactor] = cn_charactors.count(charactor) + return sorted(counter.items(),key=lambda x:x[1], reverse=True) + + +en_text = ''' +the Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those! +''' + +cn_text = ''' +Python之禅 by Tim Peters + +优美胜于丑陋 +明了胜于晦涩 +简洁胜于复杂 +复杂胜于凌乱 +扁平胜于嵌套 +间隔胜于紧凑 +可读性很重要 +尽管实用会打破纯粹,也不可违背规则 +不要包容任何错误,除非你确定需要这样做 +当存在多种可能,不要尝试去猜测 +而是尽量找一种,最好是唯一一种明显的解决方案 +虽然这并不容易,因为你不是 Python 之父 +做也许好过不做,但不假思索就动手还不如不做 +如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然 +命名空间是一种绝妙的理念,请多加利用 +''' + +if __name__ == "__main__": + en_result = stats_text_en(en_text) + cn_result = stats_text_cn(cn_text) + print('统计参数中英文单词出现次数==>\n', en_result) + print('统计参数中汉字出现次数==>\n', cn_result) \ No newline at end of file From e6337c1a925d85b38718e35e848fddd135169d98 Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Sun, 15 Sep 2019 19:39:22 +0800 Subject: [PATCH 12/14] =?UTF-8?q?Day=208=20=E4=BD=9C=E4=B8=9A=EF=BC=9A?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 考虑输入中的错误,找出并提示 --- .../1901100351/1001S02E05_stats_text1.py | 18 ++-- exercises/1901100351/d08/mymodule/main.py | 62 ++++++++++++ .../1901100351/d08/mymodule/stats_word.py | 97 +++++++++++++++++++ 3 files changed, 168 insertions(+), 9 deletions(-) create mode 100644 exercises/1901100351/d08/mymodule/main.py create mode 100644 exercises/1901100351/d08/mymodule/stats_word.py diff --git a/exercises/1901100351/1001S02E05_stats_text1.py b/exercises/1901100351/1001S02E05_stats_text1.py index 6565f179c..8ca4319be 100644 --- a/exercises/1901100351/1001S02E05_stats_text1.py +++ b/exercises/1901100351/1001S02E05_stats_text1.py @@ -22,18 +22,18 @@ Namespaces are one honking great idea -- let's do more of those! ''' -elements = sample_text.split() -words = [] -symbols = ',.*-!' -for element in elements: +elements = sample_text.split()#将sample_text分割为字符集合 +words = []#设置字符列表 +symbols = ',.*-!'#定义非字母符号 +for element in elements:#遍历字符集合 for symbol in symbols: - element = element.replace(symbol,'') - if len(element): - words.append(element) + element = element.replace(symbol,'')#用空格代替非字母符号 + if len(element):#如果字符串长度>=1 + words.append(element)#把字符串放到列表中 print('正常的英文单词==>',words) -counter = {} -word_set = set(words) +counter = {}#设置词典 +word_set = set(words)#创建无序不重复元素集 for word in word_set: counter[word] = words.count(word) diff --git a/exercises/1901100351/d08/mymodule/main.py b/exercises/1901100351/d08/mymodule/main.py new file mode 100644 index 000000000..b02989eb3 --- /dev/null +++ b/exercises/1901100351/d08/mymodule/main.py @@ -0,0 +1,62 @@ +# this is d8 exercise for erros and exceptions +# date: 2019.09.15 +# author by: rtgong + +import stats_word + +text = ''' +愚公移山 +太行,王屋二山的北面,住了一個九十歲的老翁,名叫愚公。二山佔地廣闊,擋住去路,使他和家人往來極為不便。 +一天,愚公召集家人說:「讓我們各盡其力,剷平二山,開條道路,直通豫州,你們認為怎樣?」 +大家都異口同聲贊成,只有他的妻子表示懷疑,並說:「你連開鑿一個小丘的力量都沒有,怎可能剷平太行、王屋二山呢?況且,鑿出的土石又丟到哪裏去呢?」 +大家都熱烈地說:「把土石丟進渤海裏。」 +於是愚公就和兒孫,一起開挖土,把土石搬運到渤海去。 +愚公的鄰居是個寡婦,有個兒子八歲也興致勃勃地走來幫忙。 +寒來暑往,他們要一年才能往返渤海一次。 +住在黃河河畔的智叟,看見他們這樣辛苦,取笑愚公說:「你不是很愚蠢嗎?你已一把年紀了,就是用盡你的氣力,也不能挖去山的一角呢?」 +愚公歎息道:「你有這樣的成見,是不會明白的。你比那寡婦的小兒子還不如呢!就算我死了,還有我的兒子,我的孫子,我的曾孫子,他們一直傳下去。 +而這二山是不會加大的,總有一天,我們會把它們剷平。」 +智叟聽了,無話可說: +二山的守護神被愚公的堅毅精神嚇倒,便把此事奏知天帝。天帝佩服愚公的精神,就命 +兩位大力神揹走二山。 + +17**2 + +How The Foolish Old Man Moved Mountains +Yugong was a ninety-year-old man who lived at the north +of two high mountains, Mount Taixing and Mount Wangwu. +Stretching over a wide expanse of land, the mountains blocked +yugong’s way making it inconvenient for him and his family to get around. +One day yugong gathered his family +together and said,”Let’s do our best to level these two mountains. We shall open a road that leads to Yuzhou. What +do you think?” +All but his wife agreed with him. +“You don’t have the strength to cut even a small mound,” muttered +his wife. “How on earth do you suppose you can level Mount Taixin and Mount Wanwu? Moreover, where will all the +earth and rubble go?” +“Dump them into the Sea of Bohai!” said everyone. +So Yugong, his sons, and his grandsons +started to break up rocks and remove the earth. They transported the earth and rubble to the Sea of Bohai. +Now Yugong +’s neighbour was a widow who had an only child eight years old. Evening the young boy offered his help eagerly. +Summer went by and winter came. It took Yugong and his crew a full year to travel back and forth once. +On the bank of +the Yellow River dwelled an old man much respected for his wisdom. When he saw their back-breaking labour, he +ridiculed Yugong saying,”Aren’t you foolish, my friend? You are very old now, and with whatever remains of your +waning strength, you won’t be able to remove even a corner of the mountain.” +Yugong uttered a sigh and said,”A +biased person like you will never understand. You can’t even compare with the widow’s little boy!” +“Even if I +were dead, there will still be my children, my grandchildren, my great grandchildren, my great great grandchildren. +They descendants will go on forever. But these mountains will not grow any taler. We shall level them one day!” he +declared with confidence. +The wise old man was totally silenced. +When the guardian gods of the mountains saw how +determined Yugong and his crew were, they were struck with fear and reported the incident to the Emperor of Heavens. +Filled with admiration for Yugong, the Emperor of Heavens ordered two mighty gods to carry the mountains away. +''' + +try: + print('合并词频统计结果:', stats_word.stats_text(text)) +except ValueError: + print() \ No newline at end of file diff --git a/exercises/1901100351/d08/mymodule/stats_word.py b/exercises/1901100351/d08/mymodule/stats_word.py new file mode 100644 index 000000000..bd36f7504 --- /dev/null +++ b/exercises/1901100351/d08/mymodule/stats_word.py @@ -0,0 +1,97 @@ +# this is d8 exercise for erros and exceptions +# date: 2019.09.15 +# author by: rtgong + +# 统计参数中英文单词出现的次数,并按降序排列 +def stats_text_en(text): #定义函数 + if type(text)==str: + elements = text.split()#对字符串进行切片 + words = []#设置列表 + symbols = ',.*-!' + for element in elements: + for symbol in symbols: + element = element.replace(symbol,'') + if len(element): + words.append(element) + counter = {}#创建字典 + word_set = set(words)#创建无序不重复集合 + + for word in word_set: + counter[word] = words.count(word) + return sorted(counter.items(), key=lambda x:x[1], reverse=True) + else: + raise ValueError('type of text is not str') + + +# 统计参数中汉字出现次数,并按降序排列 +def stats_text_cn(text):#设定函数 + if type(text)==str: + cn_charactors = [] + for charactor in text: + if '\u4e00'<= charactor <= '\u9fff':#中文字符的代码区间 + cn_charactors.append(charactor) + counter = {}#创建字典 + cn_charactor_set = set(cn_charactors) + for charactor in cn_charactor_set: + counter[charactor] = cn_charactors.count(charactor) + return sorted(counter.items(),key=lambda x:x[1], reverse=True) + else: + raise ValueError('type of text is not str') + +# 合并英汉词频统计 +def stats_text(text_en_cn) : + if type(text_en_cn)==str: + return (stats_text_en(text_en_cn)+stats_text_cn(text_en_cn)) + else: + raise ValueError('type of text is not str') + + +en_text = ''' +the Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those! +''' + +cn_text = ''' +Python之禅 by Tim Peters + +优美胜于丑陋 +明了胜于晦涩 +简洁胜于复杂 +复杂胜于凌乱 +扁平胜于嵌套 +间隔胜于紧凑 +可读性很重要 +尽管实用会打破纯粹,也不可违背规则 +不要包容任何错误,除非你确定需要这样做 +当存在多种可能,不要尝试去猜测 +而是尽量找一种,最好是唯一一种明显的解决方案 +虽然这并不容易,因为你不是 Python 之父 +做也许好过不做,但不假思索就动手还不如不做 +如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然 +命名空间是一种绝妙的理念,请多加利用 +''' + +if __name__ == "__main__": + en_result = stats_text_en(en_text) + cn_result = stats_text_cn(cn_text) + print('统计参数中英文单词出现次数==>\n', en_result) + print('统计参数中汉字出现次数==>\n', cn_result) \ No newline at end of file From edb4e20435b620d283d837ee418061c9b8b0d11c Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Wed, 18 Sep 2019 21:06:44 +0800 Subject: [PATCH 13/14] =?UTF-8?q?=E7=AC=AC8=E6=AC=A1=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根据视频资料,对第8次作业进行了修改 --- exercises/1901100351/d08/mymodule/main.py | 31 +++++++-- .../1901100351/d08/mymodule/stats_word.py | 65 +++++++++---------- 2 files changed, 56 insertions(+), 40 deletions(-) diff --git a/exercises/1901100351/d08/mymodule/main.py b/exercises/1901100351/d08/mymodule/main.py index b02989eb3..cd731f04a 100644 --- a/exercises/1901100351/d08/mymodule/main.py +++ b/exercises/1901100351/d08/mymodule/main.py @@ -1,8 +1,31 @@ # this is d8 exercise for erros and exceptions -# date: 2019.09.15 +# date: 2019.09.15;renew in 09.18 # author by: rtgong import stats_word +import traceback +import logging + +logger = logging.getLogger(__name__) + +def test_traceback(): + try: + stats_word.stats_text(1) + except Exception as e: + print('test_traceback =>',e) + print(traceback.format_exc()) + +def test_logger(): + try: + stats_word.stats_text(1) + except Exception as e: + logger.exception(e) + +if __name__=="__main__": + test_traceback() + test_logger() + + text = ''' 愚公移山 @@ -20,7 +43,6 @@ 二山的守護神被愚公的堅毅精神嚇倒,便把此事奏知天帝。天帝佩服愚公的精神,就命 兩位大力神揹走二山。 -17**2 How The Foolish Old Man Moved Mountains Yugong was a ninety-year-old man who lived at the north @@ -55,8 +77,3 @@ determined Yugong and his crew were, they were struck with fear and reported the incident to the Emperor of Heavens. Filled with admiration for Yugong, the Emperor of Heavens ordered two mighty gods to carry the mountains away. ''' - -try: - print('合并词频统计结果:', stats_word.stats_text(text)) -except ValueError: - print() \ No newline at end of file diff --git a/exercises/1901100351/d08/mymodule/stats_word.py b/exercises/1901100351/d08/mymodule/stats_word.py index bd36f7504..9eb4ab8e0 100644 --- a/exercises/1901100351/d08/mymodule/stats_word.py +++ b/exercises/1901100351/d08/mymodule/stats_word.py @@ -1,49 +1,48 @@ # this is d8 exercise for erros and exceptions -# date: 2019.09.15 +# date: 2019.09.15;renew in 09.18 # author by: rtgong # 统计参数中英文单词出现的次数,并按降序排列 def stats_text_en(text): #定义函数 - if type(text)==str: - elements = text.split()#对字符串进行切片 - words = []#设置列表 - symbols = ',.*-!' - for element in elements: - for symbol in symbols: - element = element.replace(symbol,'') - if len(element): - words.append(element) - counter = {}#创建字典 - word_set = set(words)#创建无序不重复集合 + if not isinstance(text,str): + raise ValueError('参数必须是 str 类型,输入类型 %s' % type(text)) + elements = text.split()#对字符串进行切片 + words = []#设置列表 + symbols = ',.*-!' + for element in elements: + for symbol in symbols: + element = element.replace(symbol,'') + if len(element): + words.append(element) + counter = {}#创建字典 + word_set = set(words)#创建无序不重复集合 - for word in word_set: - counter[word] = words.count(word) - return sorted(counter.items(), key=lambda x:x[1], reverse=True) - else: - raise ValueError('type of text is not str') + for word in word_set: + counter[word] = words.count(word) + return sorted(counter.items(), key=lambda x:x[1], reverse=True) # 统计参数中汉字出现次数,并按降序排列 def stats_text_cn(text):#设定函数 - if type(text)==str: - cn_charactors = [] - for charactor in text: - if '\u4e00'<= charactor <= '\u9fff':#中文字符的代码区间 - cn_charactors.append(charactor) - counter = {}#创建字典 - cn_charactor_set = set(cn_charactors) - for charactor in cn_charactor_set: - counter[charactor] = cn_charactors.count(charactor) - return sorted(counter.items(),key=lambda x:x[1], reverse=True) - else: - raise ValueError('type of text is not str') + if not isinstance(text,str): + raise ValueError('参数必须是 str 类型,输入类型 %s' % type(text)) + cn_charactors = [] + for charactor in text: + if '\u4e00'<= charactor <= '\u9fff':#中文字符的代码区间 + cn_charactors.append(charactor) + counter = {}#创建字典 + cn_charactor_set = set(cn_charactors) + for charactor in cn_charactor_set: + counter[charactor] = cn_charactors.count(charactor) + return sorted(counter.items(),key=lambda x:x[1], reverse=True) + # 合并英汉词频统计 def stats_text(text_en_cn) : - if type(text_en_cn)==str: - return (stats_text_en(text_en_cn)+stats_text_cn(text_en_cn)) - else: - raise ValueError('type of text is not str') + if not isinstance(text_en_cn,str): + raise ValueError('参数必须是 str 类型,输入类型 %s' % type(text_en_cn)) + return (stats_text_en(text_en_cn)+stats_text_cn(text_en_cn)) + en_text = ''' From 603a71585d2a8a49328d89f9f0434599ebf02d30 Mon Sep 17 00:00:00 2001 From: Gong Rong Ting Date: Fri, 20 Sep 2019 20:46:32 +0800 Subject: [PATCH 14/14] =?UTF-8?q?=E7=AC=AC9=E6=AC=A1=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=EF=BC=9A=E5=AD=A6=E4=B9=A0=E4=BD=BF=E7=94=A8=E6=A0=87=E5=87=86?= =?UTF-8?q?=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在第8次作业的基础上,学习使用标准库中的函数 --- exercises/1901100351/d09/mymodule/main.py | 64 +++++++++++++ .../1901100351/d09/mymodule/stats_word.py | 93 +++++++++++++++++++ 2 files changed, 157 insertions(+) create mode 100644 exercises/1901100351/d09/mymodule/main.py create mode 100644 exercises/1901100351/d09/mymodule/stats_word.py diff --git a/exercises/1901100351/d09/mymodule/main.py b/exercises/1901100351/d09/mymodule/main.py new file mode 100644 index 000000000..f2fdb33e2 --- /dev/null +++ b/exercises/1901100351/d09/mymodule/main.py @@ -0,0 +1,64 @@ +# this is d9 exercise for stander libirary +# date: 2019.09.20 +# author by: rtgong + +import stats_word + +with open(r'D:\编程学习\selfteaching-python-camp\exercises\1901100351\d09\mymodule\tang300.json',encoding='UTF-8') as f: + text = f.read() +f.closed + +print(stats_word.stats_text_cn(text)) + + + +text = ''' +愚公移山 +太行,王屋二山的北面,住了一個九十歲的老翁,名叫愚公。二山佔地廣闊,擋住去路,使他和家人往來極為不便。 +一天,愚公召集家人說:「讓我們各盡其力,剷平二山,開條道路,直通豫州,你們認為怎樣?」 +大家都異口同聲贊成,只有他的妻子表示懷疑,並說:「你連開鑿一個小丘的力量都沒有,怎可能剷平太行、王屋二山呢?況且,鑿出的土石又丟到哪裏去呢?」 +大家都熱烈地說:「把土石丟進渤海裏。」 +於是愚公就和兒孫,一起開挖土,把土石搬運到渤海去。 +愚公的鄰居是個寡婦,有個兒子八歲也興致勃勃地走來幫忙。 +寒來暑往,他們要一年才能往返渤海一次。 +住在黃河河畔的智叟,看見他們這樣辛苦,取笑愚公說:「你不是很愚蠢嗎?你已一把年紀了,就是用盡你的氣力,也不能挖去山的一角呢?」 +愚公歎息道:「你有這樣的成見,是不會明白的。你比那寡婦的小兒子還不如呢!就算我死了,還有我的兒子,我的孫子,我的曾孫子,他們一直傳下去。 +而這二山是不會加大的,總有一天,我們會把它們剷平。」 +智叟聽了,無話可說: +二山的守護神被愚公的堅毅精神嚇倒,便把此事奏知天帝。天帝佩服愚公的精神,就命 +兩位大力神揹走二山。 + + +How The Foolish Old Man Moved Mountains +Yugong was a ninety-year-old man who lived at the north +of two high mountains, Mount Taixing and Mount Wangwu. +Stretching over a wide expanse of land, the mountains blocked +yugong’s way making it inconvenient for him and his family to get around. +One day yugong gathered his family +together and said,”Let’s do our best to level these two mountains. We shall open a road that leads to Yuzhou. What +do you think?” +All but his wife agreed with him. +“You don’t have the strength to cut even a small mound,” muttered +his wife. “How on earth do you suppose you can level Mount Taixin and Mount Wanwu? Moreover, where will all the +earth and rubble go?” +“Dump them into the Sea of Bohai!” said everyone. +So Yugong, his sons, and his grandsons +started to break up rocks and remove the earth. They transported the earth and rubble to the Sea of Bohai. +Now Yugong +’s neighbour was a widow who had an only child eight years old. Evening the young boy offered his help eagerly. +Summer went by and winter came. It took Yugong and his crew a full year to travel back and forth once. +On the bank of +the Yellow River dwelled an old man much respected for his wisdom. When he saw their back-breaking labour, he +ridiculed Yugong saying,”Aren’t you foolish, my friend? You are very old now, and with whatever remains of your +waning strength, you won’t be able to remove even a corner of the mountain.” +Yugong uttered a sigh and said,”A +biased person like you will never understand. You can’t even compare with the widow’s little boy!” +“Even if I +were dead, there will still be my children, my grandchildren, my great grandchildren, my great great grandchildren. +They descendants will go on forever. But these mountains will not grow any taler. We shall level them one day!” he +declared with confidence. +The wise old man was totally silenced. +When the guardian gods of the mountains saw how +determined Yugong and his crew were, they were struck with fear and reported the incident to the Emperor of Heavens. +Filled with admiration for Yugong, the Emperor of Heavens ordered two mighty gods to carry the mountains away. +''' diff --git a/exercises/1901100351/d09/mymodule/stats_word.py b/exercises/1901100351/d09/mymodule/stats_word.py new file mode 100644 index 000000000..87ad51821 --- /dev/null +++ b/exercises/1901100351/d09/mymodule/stats_word.py @@ -0,0 +1,93 @@ +# this is d9 exercise for stander libirary +# date: 2019.09.20 +# author by: rtgong + +# 统计参数中英文单词出现的次数,并按降序排列 +def stats_text_en(text): #定义函数 + import collections + if not isinstance(text,str): + raise ValueError('参数必须是 str 类型,输入类型 %s' % type(text)) + text = text.replace(',','').replace('.','').replace('!','').replace('--','').replace('*','').replace('(','').replace(')','') + list_text = text.split() + count = int(input("请输入要限制输出的元素个数:")) + dic = collections.counter(list_text).most_common(count) + return dic + +# 统计参数中汉字出现次数,并按降序排列 +def stats_text_cn(text):#设定函数 + dic = {} + if not isinstance(text,str): + raise ValueError('参数必须是 str 类型,输入类型 %s' % type(text)) + + for i in text: + if '\u4e00'<= i <= '\u9fff':#中文字符的代码区间 + dic[i] = text.count(i) + import collections + count = int(input("请输入要限制输出的元素个数:")) + dic = collections.Counter(dic).most_common(count) + return dic + + +# 合并英汉词频统计 +def stats_text(text) : + dic_1 = stats_text_cn(text) + if not isinstance(text,str): + raise ValueError('参数必须是 str 类型,输入类型 %s' % type(text)) + for i in text: + if '\u4e00'<= i <= '\u9fff': + text = text.replace(i,'') + text = text.replace('「','').replace('」','').replace(',','').replace('。','').replace('?','').replace('!','').replace(':','') + dic_2 = stats_text_cn(text) + dic_3 = {} + dic_3.update(dic_2) + dic_3.update(dic_1) + dic_3 = sorted(dic_3.items(),key=lambda x:x[1], reverse = True) + + return(dic_3) + +print(stats_text.__doc__) + + +en_text = ''' +the Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those! +''' + +cn_text = ''' +Python之禅 by Tim Peters + +优美胜于丑陋 +明了胜于晦涩 +简洁胜于复杂 +复杂胜于凌乱 +扁平胜于嵌套 +间隔胜于紧凑 +可读性很重要 +尽管实用会打破纯粹,也不可违背规则 +不要包容任何错误,除非你确定需要这样做 +当存在多种可能,不要尝试去猜测 +而是尽量找一种,最好是唯一一种明显的解决方案 +虽然这并不容易,因为你不是 Python 之父 +做也许好过不做,但不假思索就动手还不如不做 +如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然 +命名空间是一种绝妙的理念,请多加利用 +'''