From 19e0fdd88482919db9521c82b0cde63371258610 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Mon, 1 Apr 2019 14:08:05 +0800 Subject: [PATCH 01/39] Create 1001S02E02_hello_python.py.py --- exercises/1901010072/1001S02E02_hello_python.py.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 exercises/1901010072/1001S02E02_hello_python.py.py diff --git a/exercises/1901010072/1001S02E02_hello_python.py.py b/exercises/1901010072/1001S02E02_hello_python.py.py new file mode 100644 index 000000000..795f1e43b --- /dev/null +++ b/exercises/1901010072/1001S02E02_hello_python.py.py @@ -0,0 +1 @@ +print ('hello world') From 034b8a955e6d9f412118cb32d79ac46f49f183b3 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Mon, 2 Sep 2019 13:37:48 +0800 Subject: [PATCH 02/39] Create 1001S02E03_calculator.py --- exercises/1901010072/1001S02E03_calculator.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 exercises/1901010072/1001S02E03_calculator.py diff --git a/exercises/1901010072/1001S02E03_calculator.py b/exercises/1901010072/1001S02E03_calculator.py new file mode 100644 index 000000000..6be24f017 --- /dev/null +++ b/exercises/1901010072/1001S02E03_calculator.py @@ -0,0 +1,21 @@ +def add(a: object, b: object) -> object: + """ + + :rtype: object + """ + return a + b + +a=3 +b=4 +print(add(a,b)) + +def subtract(c, d): + return c - d + + +def multiply(e, f): + return e * f + + +def divide(g, h): + return g / h From c8674089977d025eb517df8ae5b0a18890378c31 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Mon, 2 Sep 2019 23:23:27 +0800 Subject: [PATCH 03/39] Update 1001S02E03_calculator.py --- exercises/1901010072/1001S02E03_calculator.py | 59 ++++++++++++------- 1 file changed, 38 insertions(+), 21 deletions(-) diff --git a/exercises/1901010072/1001S02E03_calculator.py b/exercises/1901010072/1001S02E03_calculator.py index 6be24f017..79846138e 100644 --- a/exercises/1901010072/1001S02E03_calculator.py +++ b/exercises/1901010072/1001S02E03_calculator.py @@ -1,21 +1,38 @@ -def add(a: object, b: object) -> object: - """ - - :rtype: object - """ - return a + b - -a=3 -b=4 -print(add(a,b)) - -def subtract(c, d): - return c - d - - -def multiply(e, f): - return e * f - - -def divide(g, h): - return g / h +# 实现一个简单的计算器 +# 1 接收用户输入的第一个数字(字符串类型),并转化为整数类型int + first_num = input('请输入第一个数字:') + first_num = int(first_num) +# 2 接收用户输入的运算符 + symbol = input('请输入运算符(+,-,*,/):') +# 3 接收用户输入的第二个数字(字符串类型),并转化为整数类型int + sec_num = input('请输入第二个数字:') + sec_num = int(sec_num) +# 4 代码进行判断,计算 + if symbol == '+': + result = first_num + sec_num + print(f'{first_num}{symbol}{sec_num}={result}') + + elif symbol == '-': + result = first_num - sec_num + print(f'{first_num}{symbol}{sec_num}={result}') + + elif symbol == '*': + result = first_num * sec_num + print(f'{first_num}{symbol}{sec_num}={result}') + + elif symbol == '/': + if sec_num == 0: + result = '除数不能为0' + print(result) + else: + result = first_num / sec_num + print(f'{first_num}{symbol}{sec_num}={result}') + + else: + result = '输入错误' + print(result) + +# 5 显示计算的结果,以及完整的等式 +# 格式化输出 format + # print(result) + print(f'{first_num}{symbol}{sec_num}={result}') \ No newline at end of file From 1ee4f59593676ed64c6b333bcb4e77622b3ee55d Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Tue, 3 Sep 2019 22:38:12 +0800 Subject: [PATCH 04/39] Create 1001S02E04_control_flow.py --- .../1901010072/1001S02E04_control_flow.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 exercises/1901010072/1001S02E04_control_flow.py diff --git a/exercises/1901010072/1001S02E04_control_flow.py b/exercises/1901010072/1001S02E04_control_flow.py new file mode 100644 index 000000000..92f7e804f --- /dev/null +++ b/exercises/1901010072/1001S02E04_control_flow.py @@ -0,0 +1,23 @@ +# for in循环 + for a in range(1,10): + for b in range(1,10): + print(a,"X",b,"=",a*b,"\t",end="") + if a == b: + print("") + break + +i=0 +j=0 +while i<9: + i+=1 + if condition: i % 2 == 0: + pass + while j<9: + j+=1 + print(j,"x",i,"=",i*j,"\t",end="") + if i==j: + j=0 + print("") + break + else: print("") + break \ No newline at end of file From 85fda72e41851e55a281a7ce6fb3d89f0df4295f Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sat, 7 Sep 2019 00:07:48 +0800 Subject: [PATCH 05/39] Update 1001S02E04_control_flow.py --- .../1901010072/1001S02E04_control_flow.py | 36 ++++++++----------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/exercises/1901010072/1001S02E04_control_flow.py b/exercises/1901010072/1001S02E04_control_flow.py index 92f7e804f..c602c5af4 100644 --- a/exercises/1901010072/1001S02E04_control_flow.py +++ b/exercises/1901010072/1001S02E04_control_flow.py @@ -1,23 +1,15 @@ -# for in循环 - for a in range(1,10): - for b in range(1,10): - print(a,"X",b,"=",a*b,"\t",end="") - if a == b: - print("") - break +print('打印九九乘法表') +for i in range(1,10): + for j in range (1,i+1): + print(i,'*',j,'=',i*j,end='\t') + print() -i=0 -j=0 -while i<9: - i+=1 - if condition: i % 2 == 0: - pass - while j<9: - j+=1 - print(j,"x",i,"=",i*j,"\t",end="") - if i==j: - j=0 - print("") - break - else: print("") - break \ No newline at end of file +print('打印跳过偶数行的九九乘法表') +i = 1 +while i<10: + if i%2 ==0: + print() + else: + for j in range(1,i+1): + print(i,'*',j,'=',i*j,end='\t') + i+=1 \ No newline at end of file From 96983e51573d2a9c6fa25aced28a2c28b4260de8 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sat, 28 Sep 2019 22:14:07 +0800 Subject: [PATCH 06/39] Create 1001S02E05_array.py --- exercises/1901010072/1001S02E05_array.py | 25 ++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 exercises/1901010072/1001S02E05_array.py diff --git a/exercises/1901010072/1001S02E05_array.py b/exercises/1901010072/1001S02E05_array.py new file mode 100644 index 000000000..311ffc85a --- /dev/null +++ b/exercises/1901010072/1001S02E05_array.py @@ -0,0 +1,25 @@ +# 将数组 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 翻转 +a_list =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +list(iterable) +for i in a: +print(i,reverse=True) +a_list.reverse() +# 翻转后的数组拼接成字符串 +s='' +s.join(a) +# ⽤字符串切片的方式取出第三到第⼋个字符(包含第三和第⼋个字符) +print(a_list[3:9]) +# 将获得的字符串进行翻转 +b=a_list[3:9].reverse() +print(b) +# 将结果转换为 int 类型 +c=int(b) +print(c) +# 分别转换成⼆进制,⼋进制,十六进制 +d=bin(int(c, 2)) +e=oct(int(c, 2)) +f=hex(int(c, 2)) +# 最后输出三种进制的结果 +print(d) +print(e) +print(f) \ No newline at end of file From 9d7b2c24789134666ae9387b3247cf4f34138742 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sat, 28 Sep 2019 22:14:13 +0800 Subject: [PATCH 07/39] Create 1001S02E05_state_text.py --- exercises/1901010072/1001S02E05_state_text.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 exercises/1901010072/1001S02E05_state_text.py diff --git a/exercises/1901010072/1001S02E05_state_text.py b/exercises/1901010072/1001S02E05_state_text.py new file mode 100644 index 000000000..e61aa7815 --- /dev/null +++ b/exercises/1901010072/1001S02E05_state_text.py @@ -0,0 +1,32 @@ +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 ambxiguity, 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! +''' +# 使用字典(dict)统计字符串样本text中各个英文单词出现的次数 +# 按照出现次数从⼤到⼩输出所有的单词及出现的次数 +# 只统计英文单词,不包括⾮、非英⽂字符的其他任何符号,如连接符号、空白字符等 +s=text +s.strip() +for k in s: + v = str.count(k) +dict=dict_items([k,v]) +sorted(dict,reverse=true) \ No newline at end of file From 32384e4cccad277700cd742eaeb4d2f09a9f494a Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sat, 28 Sep 2019 22:14:18 +0800 Subject: [PATCH 08/39] Create 1001S02E05_string.py --- exercises/1901010072/1001S02E05_string.py | 43 +++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 exercises/1901010072/1001S02E05_string.py diff --git a/exercises/1901010072/1001S02E05_string.py b/exercises/1901010072/1001S02E05_string.py new file mode 100644 index 000000000..fe1975165 --- /dev/null +++ b/exercises/1901010072/1001S02E05_string.py @@ -0,0 +1,43 @@ +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 ambxiguity, 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! +''' +#第一步将字符串样本text里的better全部替换成worse +s=text +s.replace('better', 'worse', ) +print(s.replace('better', 'worse', )) + +#第二步将单词中包含ea的单词剔除 +s.split() +L = list(s) +for C in L: + if 'ea' in 'C', + del L[C] + print(L_list) +else: + print(L_list) + +#第三步将字⺟进行⼤小写翻转 +s.swapcase() + +#第四步将单词升序排列 +L_list.sort() \ No newline at end of file From 33b413b237ddf274109c4c44e1bf973b0c26b3ec Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Wed, 2 Oct 2019 01:23:51 +0800 Subject: [PATCH 09/39] Update 1001S02E05_array.py --- exercises/1901010072/1001S02E05_array.py | 55 +++++++++++++----------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/exercises/1901010072/1001S02E05_array.py b/exercises/1901010072/1001S02E05_array.py index 311ffc85a..71df3da6b 100644 --- a/exercises/1901010072/1001S02E05_array.py +++ b/exercises/1901010072/1001S02E05_array.py @@ -1,25 +1,30 @@ -# 将数组 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 翻转 -a_list =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -list(iterable) -for i in a: -print(i,reverse=True) -a_list.reverse() -# 翻转后的数组拼接成字符串 -s='' -s.join(a) -# ⽤字符串切片的方式取出第三到第⼋个字符(包含第三和第⼋个字符) -print(a_list[3:9]) -# 将获得的字符串进行翻转 -b=a_list[3:9].reverse() -print(b) -# 将结果转换为 int 类型 -c=int(b) -print(c) -# 分别转换成⼆进制,⼋进制,十六进制 -d=bin(int(c, 2)) -e=oct(int(c, 2)) -f=hex(int(c, 2)) -# 最后输出三种进制的结果 -print(d) -print(e) -print(f) \ No newline at end of file +# 1.对列表 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 翻转 +sample_list =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +reverse_list=sample_list[::-1] +print('列表翻转==>',reverse_list) + +# 2.翻转后的列表拼接成字符串 +#调用''(空字符串)str类型的join方法可以连接列表里的元素,用''(空字符串)表示连接的时候元素间不用任何字符隔开 +#因为reverse_list里面都是int类型元素,所以拼接之前要把reverse_list变成一个包含str类型元素的列表 +joined_str = ''.join([str(i) for i in reverse_list]) +print('翻转后的数组接拼成字符串-->',joined_str) + +# 3.⽤字符串切片的方式取出第三到第⼋个字符(包含第三和第⼋个字符) +# 切片的时候包含开始索引,不包含结尾的索引 +slice_str=joined_str[2:8] +print('用字符串切片的方式取出第三到第八个字符-->',sliced_str) + +# 4.将获得的字符串进行翻转 + +reversed_str=sliced_str[::-1] +print('字符串翻转-->',reversed_str) + +# 5.将结果转换为 int 类型 +int_value=int(reversed_str) +print('转换为 int 类型-->',int_value) + +# 6.分别转换成⼆进制,⼋进制,十六进制 + +print('转换为二进制==>',bin(int_value)) +print('转换为八进制==>',oct(int_value)) +print('转换为十六进制==>',hex(int_value)) From 99b8417dd123a9ca1f47a3faa946105ee167d669 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Wed, 2 Oct 2019 01:23:56 +0800 Subject: [PATCH 10/39] Update 1001S02E05_state_text.py --- exercises/1901010072/1001S02E05_state_text.py | 45 ++++++++++++++----- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/exercises/1901010072/1001S02E05_state_text.py b/exercises/1901010072/1001S02E05_state_text.py index e61aa7815..1395809c1 100644 --- a/exercises/1901010072/1001S02E05_state_text.py +++ b/exercises/1901010072/1001S02E05_state_text.py @@ -1,4 +1,4 @@ -text = ''' +sample_text = ''' The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. @@ -21,12 +21,37 @@ 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! ''' -# 使用字典(dict)统计字符串样本text中各个英文单词出现的次数 -# 按照出现次数从⼤到⼩输出所有的单词及出现的次数 -# 只统计英文单词,不包括⾮、非英⽂字符的其他任何符号,如连接符号、空白字符等 -s=text -s.strip() -for k in s: - v = str.count(k) -dict=dict_items([k,v]) -sorted(dict,reverse=true) \ No newline at end of file +# 1.使用字典(dict)统计字符串样本text中各个英文单词出现的次数 +# 先将字符串根据 空白字符 分割成list,在调用str类型 +elements = sample_text.split() +# 定义一个新的list类型变量,存储处理过的单词 +words=[] +#先针对样本文本挑选出需要提出的非单词符号 +symbols=',.*-!' +for element elements: + #遍历一遍要剔除的符号 + for symbol in symbols: + #逐个替换字符号,用''是为了同时剔除符号所占的位置 + element=elements.replace(symbol,'') + #剔除了字符后如果element的长度不为0,则算作正常单词 + if len(element): + words.append(element) +print('正常的英文单词==>',words) + +#初始化一个dict(字典)类型的数量,用来存放单词出现的次数 +count={} + +#set(集合)类型可以去掉列表里的重复元素,可以在for...in里减少循环次数 +word_set=set(words) + +for word in word_set: + counter[word]=words.count(word) + +print('英文单词出现的次数==>',counter) + +# 2.按照出现次数从⼤到⼩输出所有的单词及出现的次数 + +#内置函数sorted的参数key表示按元素的那一项的值进行排序 +#dict类型counter的items方法会返回一个包含相应项(key,value)的元组列表 +#print('counter.items()==>',counter.items()) +print('从大到小输出所有的单词及出现的次数==>',sorted(counter.items(),key=lamda x:x[],reverse=True)) From f1514e8ad04e8eb0c10dcf533b75260c9460d662 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Wed, 2 Oct 2019 01:24:03 +0800 Subject: [PATCH 11/39] Update 1001S02E05_string.py --- exercises/1901010072/1001S02E05_string.py | 33 +++++++++++++---------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/exercises/1901010072/1001S02E05_string.py b/exercises/1901010072/1001S02E05_string.py index fe1975165..eee9aeaac 100644 --- a/exercises/1901010072/1001S02E05_string.py +++ b/exercises/1901010072/1001S02E05_string.py @@ -1,4 +1,4 @@ -text = ''' +sample_text = ''' The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. @@ -22,22 +22,27 @@ Namespaces are one honking great idea -- let's do more of those! ''' #第一步将字符串样本text里的better全部替换成worse -s=text -s.replace('better', 'worse', ) -print(s.replace('better', 'worse', )) +#调用str类型的replace方法进行替换 +text=sample_text.replace('better','worse') +print('将字符串样本里的better全部替换成worse ==>', text) #第二步将单词中包含ea的单词剔除 -s.split() -L = list(s) -for C in L: - if 'ea' in 'C', - del L[C] - print(L_list) -else: - print(L_list) +#先将字符串根据 空白字符 分割成 list,在调用str类型 +words = text.split() +#定义一个list类型的变量用来存放过滤完的单词 +filtered = [] +#用 for...in 循环遍历一遍words里的元素然后判断单词是否包含ea +for word in words: + #str类型的find方法涂过不包含参数字符则返回-1,如果包含则返回该字符第一次出现时的索引 + if word.find('ea')<0: + filtered.append(word) +print('将单词中包含ea的单词剔除==>',filtered) #第三步将字⺟进行⼤小写翻转 -s.swapcase() +#利用列表推导式对str类型的元素进行大小写翻转 +swapcasd=[i.swapcase()for i in filtered] +print('进行大小写翻转-->',swapcased) #第四步将单词升序排列 -L_list.sort() \ No newline at end of file +print('单词按a...z升序排列-->',sorted(swapcased)) +#print('单词按a...z降序排列-->',sorted(swapcased,reverse=true)) \ No newline at end of file From e18bf27fb7ab2e1cdcc09e9796cff6b016883acf Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Wed, 2 Oct 2019 01:24:08 +0800 Subject: [PATCH 12/39] Create 1001S02E06_stats_word.py --- exercises/1901010072/1001S02E06_stats_word.py | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 exercises/1901010072/1001S02E06_stats_word.py diff --git a/exercises/1901010072/1001S02E06_stats_word.py b/exercises/1901010072/1001S02E06_stats_word.py new file mode 100644 index 000000000..c192a22c6 --- /dev/null +++ b/exercises/1901010072/1001S02E06_stats_word.py @@ -0,0 +1,62 @@ +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 ambxiguity, 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! +''' +# 1.统计字符串样本text中各个英文单词出现的次数 +# 先将字符串根据 空白字符 分割成list,在调用str类型 +elements = sample_text.split() +# 定义一个新的list类型变量,存储处理过的单词 +words=[] +#先针对样本文本挑选出需要提出的非单词符号 +symbols=',.*-!' +for element in elements: + #遍历一遍要剔除的符号 + for symbol in symbols: + #逐个替换字符号,用''是为了同时剔除符号所占的位置 + element=elements.replace(symbol,'') + #剔除了字符后如果element的长度不为0,则算作正常单词 + if len(element): + words.append(element) +print('正常的英文单词==>',words) + +#初始化一个dict(字典)类型的数量,用来存放单词出现的次数 +count={} + +#set(集合)类型可以去掉列表里的重复元素,可以在for...in里减少循环次数 +word_set=set(words) + +for word in word_set: + counter[word]=words.count(word) + +# 按照出现次数从⼤到⼩输出所有的单词及出现的次数进行统计、定义函数 + +def stats_text_en(sorted(counter.items(),sample_text,reverse=True)): + result={} + for word in word_set: + result[word] = word_set.count(word) + reture result + +def stats_text_cn(sorted(counter.items(),sample_text,reverse=True)): + for word in word_set: + if'\u4e00'<=word<='\u9fff': + result[word] = word_set.count(word) + reture result From 12567d15bbd52b2d6d4ab9fdee244f3b07714d14 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sun, 13 Oct 2019 01:57:41 +0800 Subject: [PATCH 13/39] Update 1001S02E05_state_text.py --- exercises/1901010072/1001S02E05_state_text.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/1901010072/1001S02E05_state_text.py b/exercises/1901010072/1001S02E05_state_text.py index 1395809c1..e4dbcbf34 100644 --- a/exercises/1901010072/1001S02E05_state_text.py +++ b/exercises/1901010072/1001S02E05_state_text.py @@ -54,4 +54,4 @@ #内置函数sorted的参数key表示按元素的那一项的值进行排序 #dict类型counter的items方法会返回一个包含相应项(key,value)的元组列表 #print('counter.items()==>',counter.items()) -print('从大到小输出所有的单词及出现的次数==>',sorted(counter.items(),key=lamda x:x[],reverse=True)) +print('从大到小输出所有的单词及出现的次数==>',sorted(counter.items(),key=lamda x:x[1],reverse=True)) From 0d2b732495d23c6799f389b41822a196d4709229 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sun, 13 Oct 2019 01:57:46 +0800 Subject: [PATCH 14/39] Update 1001S02E06_stats_word.py --- exercises/1901010072/1001S02E06_stats_word.py | 102 ++++++++++-------- 1 file changed, 60 insertions(+), 42 deletions(-) diff --git a/exercises/1901010072/1001S02E06_stats_word.py b/exercises/1901010072/1001S02E06_stats_word.py index c192a22c6..4bbab210a 100644 --- a/exercises/1901010072/1001S02E06_stats_word.py +++ b/exercises/1901010072/1001S02E06_stats_word.py @@ -1,4 +1,36 @@ -sample_text = ''' +# 统计参数中每个英文单词出现的次数 +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进行返回,如果没有return返回值则为None + return sorted(counter.items(),key=lambda x:x[1],reverse=True) + +# 统计参数中每个中文单词出现的次数 +def stats_text_cn(text): + cn_characters=[] + for character in text: + #unicode中中文字符的范围 + if '\u4e00'<=character<='\u9fff': + cn_characters.append(character) + counter={} + cn_character_set=set(cn_characters) + for character in cn_character_set: + counter[character]=cn_characters.count(character) + 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. @@ -12,51 +44,37 @@ Errors should never pass silently. Unless explicitly silenced. In the face of ambxiguity, refuse the temptation to guess. -There should be one-- and preferably only one --obvious way to do -it. +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. +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! ''' -# 1.统计字符串样本text中各个英文单词出现的次数 -# 先将字符串根据 空白字符 分割成list,在调用str类型 -elements = sample_text.split() -# 定义一个新的list类型变量,存储处理过的单词 -words=[] -#先针对样本文本挑选出需要提出的非单词符号 -symbols=',.*-!' -for element in elements: - #遍历一遍要剔除的符号 - for symbol in symbols: - #逐个替换字符号,用''是为了同时剔除符号所占的位置 - element=elements.replace(symbol,'') - #剔除了字符后如果element的长度不为0,则算作正常单词 - if len(element): - words.append(element) -print('正常的英文单词==>',words) - -#初始化一个dict(字典)类型的数量,用来存放单词出现的次数 -count={} -#set(集合)类型可以去掉列表里的重复元素,可以在for...in里减少循环次数 -word_set=set(words) - -for word in word_set: - counter[word]=words.count(word) - -# 按照出现次数从⼤到⼩输出所有的单词及出现的次数进行统计、定义函数 - -def stats_text_en(sorted(counter.items(),sample_text,reverse=True)): - result={} - for word in word_set: - result[word] = word_set.count(word) - reture result +cn_text=''' +Python之禅 by Tim Peters +优美胜于丑陋 +明了胜于晦涩 +简洁胜于复杂 +复杂胜于凌乱 +扁平胜于嵌套 +间隔胜于紧凑 +可读性很重要 +即便假借特例的实用性之名,也不可违背这些规则 +不要包容所有错误,除非你确定需要这样做 +当存在多种可能,不要尝试去猜测 +而是尽量找一种,最好是唯一一种明显的解决方案 +虽然这并不容易,因为你不是 Python 之父 +做也许好过不做,但不假思索就动手还不如不做 +如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然 +命名空间是一种绝妙的理念,我们应当多加利用。。。 +''' -def stats_text_cn(sorted(counter.items(),sample_text,reverse=True)): - for word in word_set: - if'\u4e00'<=word<='\u9fff': - result[word] = word_set.count(word) - reture result +#搜索__name__==__main}__ +#一般情况下在文件内测试代码的时候以下面的形式进行 +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 21f2f9ae1b25520c7b58d90d11ed31644ace3eca Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sun, 13 Oct 2019 01:57:51 +0800 Subject: [PATCH 15/39] Create main.py.py --- exercises/1901010072/d07/main.py.py | 71 +++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 exercises/1901010072/d07/main.py.py diff --git a/exercises/1901010072/d07/main.py.py b/exercises/1901010072/d07/main.py.py new file mode 100644 index 000000000..332d494f0 --- /dev/null +++ b/exercises/1901010072/d07/main.py.py @@ -0,0 +1,71 @@ +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. +''' + +import stats_word +text = f.read() +stats_word.stats_text(text) +def stats_text(text): + if __name__=='__main__': + en_result=stats_text_en(text) + cn_result=stats_text_cn(text) + print('统计参数中每个中英文单词出现的次数 ==>\n',en_result,cn_result) + \ No newline at end of file From df43c88d44a23ffbb9f7fcf7ab8be6b8bc2bad03 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sun, 13 Oct 2019 01:57:58 +0800 Subject: [PATCH 16/39] Create stats_word.py --- .../1901010072/d07/mymodule/stats_word.py | 104 ++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 exercises/1901010072/d07/mymodule/stats_word.py diff --git a/exercises/1901010072/d07/mymodule/stats_word.py b/exercises/1901010072/d07/mymodule/stats_word.py new file mode 100644 index 000000000..606340bb8 --- /dev/null +++ b/exercises/1901010072/d07/mymodule/stats_word.py @@ -0,0 +1,104 @@ +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. +''' + +# 统计参数中每个英文单词出现的次数 +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进行返回,如果没有return返回值则为None + return sorted(counter.items(),key=lambda x:x[1],reverse=True) + +# 统计参数中每个中文单词出现的次数 +def stats_text_cn(text): + cn_characters=[] + for character in text: + #unicode中中文字符的范围 + if '\u4e00'<=character<='\u9fff': + cn_characters.append(character) + counter={} + cn_character_set=set(cn_characters) + for character in cn_character_set: + counter[character]=cn_characters.count(character) + return sorted(counter.items(),key=lambda x:x[1],reverse=True) + +# 添加名为 stats_text的函数,实现功能:分别调用stats_text_en , stats_text_cn ,输出合并词频统计结果 +def stats_text(text): + if __name__=='__main__': + en_result=stats_text_en(text) + cn_result=stats_text_cn(text) + print('统计参数中每个中英文单词出现的次数 ==>\n',en_result,cn_result) + + """ + Return a list of frequency of each English alphabet and Chinese characters, + Sorted in descending order. + """ From 07152c69f2f96fdffc08cdcae3bed1edebf4104a Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sun, 13 Oct 2019 02:15:54 +0800 Subject: [PATCH 17/39] Update stats_word.py --- exercises/1901010072/d07/mymodule/stats_word.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/exercises/1901010072/d07/mymodule/stats_word.py b/exercises/1901010072/d07/mymodule/stats_word.py index 606340bb8..ca7dfdea1 100644 --- a/exercises/1901010072/d07/mymodule/stats_word.py +++ b/exercises/1901010072/d07/mymodule/stats_word.py @@ -92,11 +92,12 @@ def stats_text_cn(text): return sorted(counter.items(),key=lambda x:x[1],reverse=True) # 添加名为 stats_text的函数,实现功能:分别调用stats_text_en , stats_text_cn ,输出合并词频统计结果 + def stats_text(text): if __name__=='__main__': en_result=stats_text_en(text) cn_result=stats_text_cn(text) - print('统计参数中每个中英文单词出现的次数 ==>\n',en_result,cn_result) + print('统计参数中各中英文单词出现的次数 ==>\n',en_result,cn_result) """ Return a list of frequency of each English alphabet and Chinese characters, From 3e652e20adbe9e8d5b9c4fb847d2c0be85d7195e Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sun, 13 Oct 2019 23:17:35 +0800 Subject: [PATCH 18/39] Update 1001S02E05_array.py --- exercises/1901010072/1001S02E05_array.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/exercises/1901010072/1001S02E05_array.py b/exercises/1901010072/1001S02E05_array.py index 71df3da6b..2b0f24bc4 100644 --- a/exercises/1901010072/1001S02E05_array.py +++ b/exercises/1901010072/1001S02E05_array.py @@ -1,3 +1,4 @@ + # 1.对列表 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 翻转 sample_list =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] reverse_list=sample_list[::-1] @@ -28,3 +29,5 @@ print('转换为二进制==>',bin(int_value)) print('转换为八进制==>',oct(int_value)) print('转换为十六进制==>',hex(int_value)) + + From 2e478aa9174eff860b2db8a00437cf4208262558 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sun, 13 Oct 2019 23:17:41 +0800 Subject: [PATCH 19/39] Update 1001S02E05_state_text.py --- exercises/1901010072/1001S02E05_state_text.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/exercises/1901010072/1001S02E05_state_text.py b/exercises/1901010072/1001S02E05_state_text.py index e4dbcbf34..43a26db07 100644 --- a/exercises/1901010072/1001S02E05_state_text.py +++ b/exercises/1901010072/1001S02E05_state_text.py @@ -1,4 +1,6 @@ + sample_text = ''' + The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. @@ -21,6 +23,7 @@ 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! ''' + # 1.使用字典(dict)统计字符串样本text中各个英文单词出现的次数 # 先将字符串根据 空白字符 分割成list,在调用str类型 elements = sample_text.split() @@ -54,4 +57,7 @@ #内置函数sorted的参数key表示按元素的那一项的值进行排序 #dict类型counter的items方法会返回一个包含相应项(key,value)的元组列表 #print('counter.items()==>',counter.items()) + print('从大到小输出所有的单词及出现的次数==>',sorted(counter.items(),key=lamda x:x[1],reverse=True)) + + From cf384d43b024950042b31cd6d170ca9912b13610 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Sun, 13 Oct 2019 23:17:45 +0800 Subject: [PATCH 20/39] Update 1001S02E05_string.py --- exercises/1901010072/1001S02E05_string.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/exercises/1901010072/1001S02E05_string.py b/exercises/1901010072/1001S02E05_string.py index eee9aeaac..1640cc4a8 100644 --- a/exercises/1901010072/1001S02E05_string.py +++ b/exercises/1901010072/1001S02E05_string.py @@ -1,4 +1,6 @@ + sample_text = ''' + The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. @@ -22,6 +24,7 @@ Namespaces are one honking great idea -- let's do more of those! ''' #第一步将字符串样本text里的better全部替换成worse + #调用str类型的replace方法进行替换 text=sample_text.replace('better','worse') print('将字符串样本里的better全部替换成worse ==>', text) @@ -45,4 +48,4 @@ #第四步将单词升序排列 print('单词按a...z升序排列-->',sorted(swapcased)) -#print('单词按a...z降序排列-->',sorted(swapcased,reverse=true)) \ No newline at end of file +#print('单词按a...z降序排列-->',sorted(swapcased,reverse=true)) From c25c1481b9d9044a5febec5d0849ae6576ace9ec Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Wed, 16 Oct 2019 21:47:27 +0800 Subject: [PATCH 21/39] Update main.py.py --- exercises/1901010072/d07/main.py.py | 63 +++++++++-------------------- 1 file changed, 19 insertions(+), 44 deletions(-) diff --git a/exercises/1901010072/d07/main.py.py b/exercises/1901010072/d07/main.py.py index d74f7a0e6..6150d7b82 100644 --- a/exercises/1901010072/d07/main.py.py +++ b/exercises/1901010072/d07/main.py.py @@ -1,4 +1,6 @@ -text = ''' +from mymodule import stats_word + +sample_text = ''' 愚公移⼭ 太行,王屋⼆山的北面,住了一個九十歲的⽼翁,名叫愚公。⼆山佔地廣闊,擋住去路路,使他 和家⼈往來極為不便。 @@ -20,53 +22,26 @@ 力神揹走⼆山。 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?” +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 +“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. +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. +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. ''' -import stats_word +result = stats_word.stats_text(sample_text) -text = f.read() -stats_word.stats_text(text) -def stats_text(text): - if __name__=='__main__': - en_result=stats_text_en(text) - cn_result=stats_text_cn(text) - print('统计参数中各中英文单词出现的次数 ==>\n',en_result,cn_result) - \ No newline at end of file +print('统计结果==>',result) \ No newline at end of file From 821e80c9a0c6a3187203e58d6a64d9d324756843 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Wed, 16 Oct 2019 21:47:33 +0800 Subject: [PATCH 22/39] Update stats_word.py --- .../1901010072/d07/mymodule/stats_word.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/exercises/1901010072/d07/mymodule/stats_word.py b/exercises/1901010072/d07/mymodule/stats_word.py index ca7dfdea1..38e14dba6 100644 --- a/exercises/1901010072/d07/mymodule/stats_word.py +++ b/exercises/1901010072/d07/mymodule/stats_word.py @@ -68,7 +68,8 @@ def stats_text_en(text): for element in elements: for symbol in symbols: element = element.replace(symbol,'') - if len(element): + # 用str 类型的 isascii 方法判断是否是英文单词 + if len(element) and element.isascii(): words.append(element) counter={} word_set=set(words) @@ -94,12 +95,18 @@ def stats_text_cn(text): # 添加名为 stats_text的函数,实现功能:分别调用stats_text_en , stats_text_cn ,输出合并词频统计结果 def stats_text(text): - if __name__=='__main__': - en_result=stats_text_en(text) - cn_result=stats_text_cn(text) - print('统计参数中各中英文单词出现的次数 ==>\n',en_result,cn_result) - """ Return a list of frequency of each English alphabet and Chinese characters, Sorted in descending order. + 合并 英文词频和中文词频 的结果 """ + return stats_text_en(text)+stats_text_cn(text) + + +#搜索 _name_ == '_main_' +#一般情况下在文件内测试代码的时候以下面的形式进行 +if __name__=='__main__': + en_text=''' +the Zen of Python, by Tim Peters + + From 5c997ea2784f917a788936cc33e22386f25165f4 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Thu, 17 Oct 2019 13:14:20 +0800 Subject: [PATCH 23/39] Create main.py.py --- exercises/1901010072/d08/main.py.py | 53 +++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 exercises/1901010072/d08/main.py.py diff --git a/exercises/1901010072/d08/main.py.py b/exercises/1901010072/d08/main.py.py new file mode 100644 index 000000000..569145b24 --- /dev/null +++ b/exercises/1901010072/d08/main.py.py @@ -0,0 +1,53 @@ +from mymodule import stats_word + +sample_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. +''' + +result = stats_word.stats_text(sample_text) + +test = 1 # 用 try except 捕获异常并执行 +try: + stats_word.stats_text(test,100) +except ValueError: + print("input is not string, you may check again!") + +stats_word.stats_text(text,100) \ No newline at end of file From 67d26eb02b50032320e6019d74d474e26e001b72 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Thu, 17 Oct 2019 13:14:25 +0800 Subject: [PATCH 24/39] Create stats_word.py --- .../1901010072/d08/mymodule/stats_word.py | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 exercises/1901010072/d08/mymodule/stats_word.py diff --git a/exercises/1901010072/d08/mymodule/stats_word.py b/exercises/1901010072/d08/mymodule/stats_word.py new file mode 100644 index 000000000..40818e7a6 --- /dev/null +++ b/exercises/1901010072/d08/mymodule/stats_word.py @@ -0,0 +1,84 @@ +text = ''' +愚公移⼭ +太行,王屋⼆山的北面,住了一個九十歲的⽼翁,名叫愚公。⼆山佔地廣闊,擋住去路路,使他和家⼈往來極為不便。 +⼀天,愚公召集家⼈人說:「讓我們各盡其力,剷平⼆山,開條道路,直通豫州,你們認為怎樣?」 +⼤家都異異⼝同聲贊成,只有他的妻子表示懷疑,並說:「你連開鑿一個⼩丘的⼒量都沒有,怎可能剷平太行、王屋⼆山呢?況且,鑿出的⼟石⼜丟到哪裏去呢?」 +⼤家都熱烈地說:「把⼟石丟進渤海海裏。」 +於是愚公就和兒孫,⼀起開挖土,把⼟石搬運到渤海去。愚公的鄰居是個寡婦,有個兒⼦八歲也興致勃地⾛來幫忙。 +寒來暑往,他們要一年才能往返渤海一次。 +住在⿈河畔的智叟,看見他們這樣辛苦,取笑愚公說:「你不是很愚蠢嗎?你已一把年紀了,就是⽤盡你的氣力,也不能挖去山的一角呢?」 +愚公歎息道:「你有這樣的成見,是不會明白的。你⽐那寡婦的⼩兒子還不如呢!就算我死了,還有我的兒子,我的孫⼦,我的曾孫⼦,他們一直傳下去。⽽這⼆山是不會加大的,總有 +⼀天,我們會把它們剷平。」 +智叟聽了,無話可說: +⼆山的守護神被愚公的堅毅精神嚇倒,便把此事奏知天帝。天帝佩服愚公的精神,就命兩位⼤力神揹走⼆山。 + +How The Foolish Old Man Moved Mountains +Yugong was a ninety-year-old man who lived at the north of two highmountains, 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. +''' + +# 统计参数中每个英文单词出现的次数 +def stats_text_en(text): + elements=text.split() + words=[] + symbols=',.*-!' + for element in elements: + for symbol in symbols: + element = element.replace(symbol,'') + # 用str 类型的 isascii 方法判断是否是英文单词 + if len(element) and element.isascii(): + words.append(element) + counter={} + word_set=set(words) + + for word in word_set: + counter[word]=words.count(word) + #函数返回值用return进行返回,如果没有return返回值则为None + return sorted(counter.items(),key=lambda x:x[1],reverse=True) + +# 统计参数中每个中文单词出现的次数 +def stats_text_cn(text): + cn_characters=[] + for character in text: + #unicode中中文字符的范围 + if '\u4e00'<=character<='\u9fff': + cn_characters.append(character) + counter={} + cn_character_set=set(cn_characters) + for character in cn_character_set: + counter[character]=cn_characters.count(character) + return sorted(counter.items(),key=lambda x:x[1],reverse=True) + +# 添加名为 stats_text的函数,实现功能:分别调用stats_text_en , stats_text_cn ,输出合并词频统计结果 + +def stats_text(text): + """ + Return a list of frequency of each English alphabet and Chinese characters, + Sorted in descending order. + 合并 英文词频和中文词频 的结果 + """ + return stats_text_en(text)+stats_text_cn(text) + + +try: + f = open('stats_text.txt', 'r') +except FileNotFoundError as fnf_error: + print(fnf_error) From c6c5b9d96533b9f68da53828f4ad39c830880efa Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Thu, 21 Nov 2019 23:37:11 +0800 Subject: [PATCH 25/39] Create stats_word.py --- .../1901010072/d09/mymodule/stats_word.py | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 exercises/1901010072/d09/mymodule/stats_word.py diff --git a/exercises/1901010072/d09/mymodule/stats_word.py b/exercises/1901010072/d09/mymodule/stats_word.py new file mode 100644 index 000000000..2606cb019 --- /dev/null +++ b/exercises/1901010072/d09/mymodule/stats_word.py @@ -0,0 +1,62 @@ +text = ''' +愚公移⼭ +太行,王屋⼆山的北面,住了一個九十歲的⽼翁,名叫愚公。⼆山佔地廣闊,擋住去路路,使他和家⼈往來極為不便。 +⼀天,愚公召集家⼈人說:「讓我們各盡其力,剷平⼆山,開條道路,直通豫州,你們認為怎樣?」 +⼤家都異異⼝同聲贊成,只有他的妻子表示懷疑,並說:「你連開鑿一個⼩丘的⼒量都沒有,怎可能剷平太行、王屋⼆山呢?況且,鑿出的⼟石⼜丟到哪裏去呢?」 +⼤家都熱烈地說:「把⼟石丟進渤海海裏。」 +於是愚公就和兒孫,⼀起開挖土,把⼟石搬運到渤海去。愚公的鄰居是個寡婦,有個兒⼦八歲也興致勃地⾛來幫忙。 +寒來暑往,他們要一年才能往返渤海一次。 +住在⿈河畔的智叟,看見他們這樣辛苦,取笑愚公說:「你不是很愚蠢嗎?你已一把年紀了,就是⽤盡你的氣力,也不能挖去山的一角呢?」 +愚公歎息道:「你有這樣的成見,是不會明白的。你⽐那寡婦的⼩兒子還不如呢!就算我死了,還有我的兒子,我的孫⼦,我的曾孫⼦,他們一直傳下去。⽽這⼆山是不會加大的,總有 +⼀天,我們會把它們剷平。」 +智叟聽了,無話可說: +⼆山的守護神被愚公的堅毅精神嚇倒,便把此事奏知天帝。天帝佩服愚公的精神,就命兩位⼤力神揹走⼆山。 + +How The Foolish Old Man Moved Mountains +Yugong was a ninety-year-old man who lived at the north of two highmountains, 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. +''' + +import re +import collections +count=int() #int() 函数用于将一个字符串或数字转换为整型 +def stats_text_cn(text,count): + if not isinstance(text,str): + raise ValueError('type of argumengt is not str') + p=re.compile(u'[\u4e00-\u9fa5]') + a=re.findall(p,text) + str1=''.join(a) + return(collections.Counter(str1).most_common(count)) + #Counter为每个出现的英文单词计数,返回前count个词频最高的词及出现的次数. + #以int整数类型作为输出限制,使输出的元素count为整数。 +def stats_text_en(text,count): + if type(text) == str: + b=re.sub(r'[^A-Za-z]',' ',text) + list1=b.split() + return(collections.Counter(list1).most_common(count)) + else: + raise ValueError('type of argumengt is not str') +def stats_text(text,count): + if not isinstance(text,str): + raise ValueError('type of argumengt is not str') + stats_text_cn(text,count) + stats_text_en(text,count) +stats_text(text,count) \ No newline at end of file From 98b26d2d3fb13ef22ed1d9c0e939536e4adcd859 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Thu, 21 Nov 2019 23:37:17 +0800 Subject: [PATCH 26/39] Create main.py.py --- exercises/1901010072/d09/main.py.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 exercises/1901010072/d09/main.py.py diff --git a/exercises/1901010072/d09/main.py.py b/exercises/1901010072/d09/main.py.py new file mode 100644 index 000000000..a6659dbfd --- /dev/null +++ b/exercises/1901010072/d09/main.py.py @@ -0,0 +1,9 @@ +from mymodule import stats_word +import json +#路径前+r,避免转义。 +with open(r'C:\Users\CS-Mu\Documents\selfteaching-python-camp\exercises\1901010072\d09\tang300.json',encoding='UTF-8') as f: + read_date = f.read() +try: + print('统计汉字字频最高的前100个字: \n',stats_word.stats_text_cn(read_date,100)) +except ValueError as e: + print(e) \ No newline at end of file From fd911fd735ea3d6f8f0bcfb2453baeb47d11c4ff Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Thu, 21 Nov 2019 23:37:23 +0800 Subject: [PATCH 27/39] Update main.py.py --- exercises/1901010072/d08/main.py.py | 38 ++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/exercises/1901010072/d08/main.py.py b/exercises/1901010072/d08/main.py.py index 569145b24..50c352e87 100644 --- a/exercises/1901010072/d08/main.py.py +++ b/exercises/1901010072/d08/main.py.py @@ -1,6 +1,30 @@ from mymodule import stats_word +import traceback +import logging -sample_text = ''' +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: + #print('test_logger =>',e) + logger.exception(e) + +if __name__=="__main__": + #stats_word.stats_text(1) + test_traceback() + test_logger() + + +text = ''' 愚公移⼭ 太行,王屋⼆山的北面,住了一個九十歲的⽼翁,名叫愚公。⼆山佔地廣闊,擋住去路路,使他 和家⼈往來極為不便。 @@ -40,14 +64,4 @@ 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. -''' - -result = stats_word.stats_text(sample_text) - -test = 1 # 用 try except 捕获异常并执行 -try: - stats_word.stats_text(test,100) -except ValueError: - print("input is not string, you may check again!") - -stats_word.stats_text(text,100) \ No newline at end of file +''' \ No newline at end of file From c741a4e02a5667d1c60ffc570b693d1b99838ef2 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Mon, 25 Nov 2019 23:17:46 +0800 Subject: [PATCH 28/39] Update main.py.py --- exercises/1901010072/d09/main.py.py | 53 +++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 7 deletions(-) diff --git a/exercises/1901010072/d09/main.py.py b/exercises/1901010072/d09/main.py.py index a6659dbfd..448e8c25c 100644 --- a/exercises/1901010072/d09/main.py.py +++ b/exercises/1901010072/d09/main.py.py @@ -1,9 +1,48 @@ from mymodule import stats_word +from os import path import json -#路径前+r,避免转义。 -with open(r'C:\Users\CS-Mu\Documents\selfteaching-python-camp\exercises\1901010072\d09\tang300.json',encoding='UTF-8') as f: - read_date = f.read() -try: - print('统计汉字字频最高的前100个字: \n',stats_word.stats_text_cn(read_date,100)) -except ValueError as e: - print(e) \ No newline at end of file +import re +import logging + +logging.basicConfig(format='file:%(filename)s|line:%(lineno)d|message:%(message)s',level=logging.DEBUG) + +def load_file(): + ''' + 1. + 下面是常用的获取文件路径的方式,要确保tang300.json跟当前文件在同一个文件夹下,这两种方式等价 + file_path=path.join(path.dirname(path.abspath(_file_)),'./tang300.json') + ''' + file_path=path.join(path.dirname(path.abspath(__file__)),'tang300.json') + print('当前文件路径:',__file__,'\n读取文件路径:',file_path) + ''' + 2. + 这种方式表示tang300.json在当前文件的上一级目录 + file_path=path.join(path.dirname(path.abspath(__file)),'../tang300.json') + print(__file__,file_path) + + 3. + 这种方式表示tang300.json在当前文件的上一级目录的data文件夹下 + file_path=path.join(path.dirname(path.abspath(__file__)),'../data/tang300.json') + print(__file__,file_path) + ''' + with open(file_path,'r',encoding='utf-8')as f: + return f.read() + +def merge_poems(data): + poems='' + for item in data: + poems += item.get('contents','') + return poems + +def main(): + try: + data=load_file() + logging.info(data[0]) + poems=merge_poems(json.loads(data)) + logging.info('result==>%s',stats_word.stats_text_cn(poems,100)) + except Exception as e: + logging.exception(e) + + if __name__=="__main__": + main() + \ No newline at end of file From 72fccba4a913d876c1d095b7e46ec048f5d062dc Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Mon, 25 Nov 2019 23:17:51 +0800 Subject: [PATCH 29/39] Update stats_word.py --- .../1901010072/d09/mymodule/stats_word.py | 88 ++++++------------- 1 file changed, 29 insertions(+), 59 deletions(-) diff --git a/exercises/1901010072/d09/mymodule/stats_word.py b/exercises/1901010072/d09/mymodule/stats_word.py index 2606cb019..2b91b9ba0 100644 --- a/exercises/1901010072/d09/mymodule/stats_word.py +++ b/exercises/1901010072/d09/mymodule/stats_word.py @@ -1,62 +1,32 @@ -text = ''' -愚公移⼭ -太行,王屋⼆山的北面,住了一個九十歲的⽼翁,名叫愚公。⼆山佔地廣闊,擋住去路路,使他和家⼈往來極為不便。 -⼀天,愚公召集家⼈人說:「讓我們各盡其力,剷平⼆山,開條道路,直通豫州,你們認為怎樣?」 -⼤家都異異⼝同聲贊成,只有他的妻子表示懷疑,並說:「你連開鑿一個⼩丘的⼒量都沒有,怎可能剷平太行、王屋⼆山呢?況且,鑿出的⼟石⼜丟到哪裏去呢?」 -⼤家都熱烈地說:「把⼟石丟進渤海海裏。」 -於是愚公就和兒孫,⼀起開挖土,把⼟石搬運到渤海去。愚公的鄰居是個寡婦,有個兒⼦八歲也興致勃地⾛來幫忙。 -寒來暑往,他們要一年才能往返渤海一次。 -住在⿈河畔的智叟,看見他們這樣辛苦,取笑愚公說:「你不是很愚蠢嗎?你已一把年紀了,就是⽤盡你的氣力,也不能挖去山的一角呢?」 -愚公歎息道:「你有這樣的成見,是不會明白的。你⽐那寡婦的⼩兒子還不如呢!就算我死了,還有我的兒子,我的孫⼦,我的曾孫⼦,他們一直傳下去。⽽這⼆山是不會加大的,總有 -⼀天,我們會把它們剷平。」 -智叟聽了,無話可說: -⼆山的守護神被愚公的堅毅精神嚇倒,便把此事奏知天帝。天帝佩服愚公的精神,就命兩位⼤力神揹走⼆山。 +from collections import Counter -How The Foolish Old Man Moved Mountains -Yugong was a ninety-year-old man who lived at the north of two highmountains, 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. -''' - -import re -import collections -count=int() #int() 函数用于将一个字符串或数字转换为整型 -def stats_text_cn(text,count): - if not isinstance(text,str): - raise ValueError('type of argumengt is not str') - p=re.compile(u'[\u4e00-\u9fa5]') - a=re.findall(p,text) - str1=''.join(a) - return(collections.Counter(str1).most_common(count)) - #Counter为每个出现的英文单词计数,返回前count个词频最高的词及出现的次数. - #以int整数类型作为输出限制,使输出的元素count为整数。 +#统计参数中每个英文单词出现的次数 def stats_text_en(text,count): - if type(text) == str: - b=re.sub(r'[^A-Za-z]',' ',text) - list1=b.split() - return(collections.Counter(list1).most_common(count)) - else: - raise ValueError('type of argumengt is not str') -def stats_text(text,count): + elements=text.split() + words=[] + symbols=',.*-!' + for elements in elements: + for symbol in symbols: + element=element.replace(symbol,'') + #用str类型的isascii方法判断是否是英文单词 + if len(element) and element.isascii(): + words.append(element) + return Counter(words).most_common(count) + + +#统计参数中每个中文汉字出现的次数 +def stats_text_cn(text, count): + cn_characters=[] + for character in text: + #unicode中中文字符的范围 + if '\u4e00'<=character<='\u9fff': + cn_characters.append(character) + return Counter(cn_characters).most_common(count) + +def stats_text(text,count): + ''' + 合并英文词频和中文词频的结果 + ''' if not isinstance(text,str): - raise ValueError('type of argumengt is not str') - stats_text_cn(text,count) - stats_text_en(text,count) -stats_text(text,count) \ No newline at end of file + raise ValueError('参数必须是str类型,输入类型%s'%type(text)) + return stats_text_en(text,count)+stats_text_cn(text,count) \ No newline at end of file From 5008da9834ada211f7c0756e3afe03fdb16be630 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Mon, 25 Nov 2019 23:17:55 +0800 Subject: [PATCH 30/39] Create stats_word.py --- .../1901010072/d10/mymodule/stats_word.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 exercises/1901010072/d10/mymodule/stats_word.py diff --git a/exercises/1901010072/d10/mymodule/stats_word.py b/exercises/1901010072/d10/mymodule/stats_word.py new file mode 100644 index 000000000..35e250ace --- /dev/null +++ b/exercises/1901010072/d10/mymodule/stats_word.py @@ -0,0 +1,21 @@ +from collections import Counter +import jieba +seg_list = jieba.cut("text", cut_all=False) +print("Default Mode: " + "/ ".join(seg_list)) + + +#统计参数中每个中文汉字出现的次数 +def stats_text_cn(text, count): + cn_characters=[] + for character in text: + if '\u4e00'<=character<='\u9fff'and len(character)>=2: + cn_characters.append(character) + return Counter(cn_characters).most_common(20) + +def stats_text(text,count): + ''' + 合并英文词频和中文词频的结果 + ''' + if not isinstance(text,str): + raise ValueError('参数必须是str类型,输入类型%s'%type(text)) + return stats_text_cn(text,count) \ No newline at end of file From afc669d96b7d41777fdfb40a91521fb0815b8a06 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Mon, 25 Nov 2019 23:18:02 +0800 Subject: [PATCH 31/39] Create main.py.py --- exercises/1901010072/d10/main.py.py | 48 +++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 exercises/1901010072/d10/main.py.py diff --git a/exercises/1901010072/d10/main.py.py b/exercises/1901010072/d10/main.py.py new file mode 100644 index 000000000..448e8c25c --- /dev/null +++ b/exercises/1901010072/d10/main.py.py @@ -0,0 +1,48 @@ +from mymodule import stats_word +from os import path +import json +import re +import logging + +logging.basicConfig(format='file:%(filename)s|line:%(lineno)d|message:%(message)s',level=logging.DEBUG) + +def load_file(): + ''' + 1. + 下面是常用的获取文件路径的方式,要确保tang300.json跟当前文件在同一个文件夹下,这两种方式等价 + file_path=path.join(path.dirname(path.abspath(_file_)),'./tang300.json') + ''' + file_path=path.join(path.dirname(path.abspath(__file__)),'tang300.json') + print('当前文件路径:',__file__,'\n读取文件路径:',file_path) + ''' + 2. + 这种方式表示tang300.json在当前文件的上一级目录 + file_path=path.join(path.dirname(path.abspath(__file)),'../tang300.json') + print(__file__,file_path) + + 3. + 这种方式表示tang300.json在当前文件的上一级目录的data文件夹下 + file_path=path.join(path.dirname(path.abspath(__file__)),'../data/tang300.json') + print(__file__,file_path) + ''' + with open(file_path,'r',encoding='utf-8')as f: + return f.read() + +def merge_poems(data): + poems='' + for item in data: + poems += item.get('contents','') + return poems + +def main(): + try: + data=load_file() + logging.info(data[0]) + poems=merge_poems(json.loads(data)) + logging.info('result==>%s',stats_word.stats_text_cn(poems,100)) + except Exception as e: + logging.exception(e) + + if __name__=="__main__": + main() + \ No newline at end of file From 90f6abbd7f69b39fc1883770b2e72e213cda8f05 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Tue, 3 Dec 2019 00:13:53 +0800 Subject: [PATCH 32/39] Update main.py.py --- exercises/1901010072/d10/main.py.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/1901010072/d10/main.py.py b/exercises/1901010072/d10/main.py.py index 448e8c25c..4cf980dcc 100644 --- a/exercises/1901010072/d10/main.py.py +++ b/exercises/1901010072/d10/main.py.py @@ -37,7 +37,7 @@ def merge_poems(data): def main(): try: data=load_file() - logging.info(data[0]) + #logging.info(data) poems=merge_poems(json.loads(data)) logging.info('result==>%s',stats_word.stats_text_cn(poems,100)) except Exception as e: From 5836aacf274d958fd4d1de7c59ad5f5a37ac407b Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Tue, 3 Dec 2019 00:13:56 +0800 Subject: [PATCH 33/39] Create main.py.py --- exercises/1901010072/d11/main.py.py | 48 +++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 exercises/1901010072/d11/main.py.py diff --git a/exercises/1901010072/d11/main.py.py b/exercises/1901010072/d11/main.py.py new file mode 100644 index 000000000..4cf980dcc --- /dev/null +++ b/exercises/1901010072/d11/main.py.py @@ -0,0 +1,48 @@ +from mymodule import stats_word +from os import path +import json +import re +import logging + +logging.basicConfig(format='file:%(filename)s|line:%(lineno)d|message:%(message)s',level=logging.DEBUG) + +def load_file(): + ''' + 1. + 下面是常用的获取文件路径的方式,要确保tang300.json跟当前文件在同一个文件夹下,这两种方式等价 + file_path=path.join(path.dirname(path.abspath(_file_)),'./tang300.json') + ''' + file_path=path.join(path.dirname(path.abspath(__file__)),'tang300.json') + print('当前文件路径:',__file__,'\n读取文件路径:',file_path) + ''' + 2. + 这种方式表示tang300.json在当前文件的上一级目录 + file_path=path.join(path.dirname(path.abspath(__file)),'../tang300.json') + print(__file__,file_path) + + 3. + 这种方式表示tang300.json在当前文件的上一级目录的data文件夹下 + file_path=path.join(path.dirname(path.abspath(__file__)),'../data/tang300.json') + print(__file__,file_path) + ''' + with open(file_path,'r',encoding='utf-8')as f: + return f.read() + +def merge_poems(data): + poems='' + for item in data: + poems += item.get('contents','') + return poems + +def main(): + try: + data=load_file() + #logging.info(data) + poems=merge_poems(json.loads(data)) + logging.info('result==>%s',stats_word.stats_text_cn(poems,100)) + except Exception as e: + logging.exception(e) + + if __name__=="__main__": + main() + \ No newline at end of file From 4b706d5d0fd41a1e85018dcd6975cf598e6e7830 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Tue, 3 Dec 2019 00:14:00 +0800 Subject: [PATCH 34/39] Update stats_word.py --- .../1901010072/d10/mymodule/stats_word.py | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/exercises/1901010072/d10/mymodule/stats_word.py b/exercises/1901010072/d10/mymodule/stats_word.py index 35e250ace..ff47d6e16 100644 --- a/exercises/1901010072/d10/mymodule/stats_word.py +++ b/exercises/1901010072/d10/mymodule/stats_word.py @@ -1,16 +1,27 @@ from collections import Counter import jieba -seg_list = jieba.cut("text", cut_all=False) -print("Default Mode: " + "/ ".join(seg_list)) - +#pip install -i http://pypi.tuna.tsinghua.edu.cn/simple jieba +#统计参数中每个英文单词出现的次数 +def stats_text_en(text,count): + elements=text.split() + words=[] + symbols=',.*-!' + for element in elements: + for symbol in symbols: + element=element.replace(symbol,'') + #用str类型的isascii方法判断是否是英文单词 + if len(element) and element.isascii(): + words.append(element) + return Counter(words).most_common(count) #统计参数中每个中文汉字出现的次数 -def stats_text_cn(text, count): - cn_characters=[] - for character in text: - if '\u4e00'<=character<='\u9fff'and len(character)>=2: - cn_characters.append(character) - return Counter(cn_characters).most_common(20) +def stats_text_cn(text,count): + words=jieba.cut(text) + tmp=[] + for i in words: + if len(i)>1: + tmp.append(i) + return Counter(tmp).most_common(count) def stats_text(text,count): ''' From 21933f85af281604d4af7868759e92a3fc6361b7 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Tue, 3 Dec 2019 00:14:04 +0800 Subject: [PATCH 35/39] Create stats_word.py --- .../1901010072/d11/mymodule/stats_word.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 exercises/1901010072/d11/mymodule/stats_word.py diff --git a/exercises/1901010072/d11/mymodule/stats_word.py b/exercises/1901010072/d11/mymodule/stats_word.py new file mode 100644 index 000000000..7dc9790e2 --- /dev/null +++ b/exercises/1901010072/d11/mymodule/stats_word.py @@ -0,0 +1,32 @@ +import requests +from pyquery import PyQuery +import re +import jieba +from collections import Counter +import getpass +import yagmail + +'''获取目标目标网页内容,类型是一个HTTP''' +response=requests.get("https://mp.weixin.qq.com/s/pLmuGoc4bZrMNl7MSoWgiA") +'''提取http文件中p之间的内容''' +document = PyQuery(response.text) +content = document('p').text() + + +'''用正则去掉文本中的数字,字母和符号''' +content = re.sub('[a-zA-Z0-9’!"%&\'^\s+|\s+$()*+,-./:;,。?、…?“”‘’!]+',"",content) +'''用jieba将文本进行全模式切分''' +seg_list = jieba.cut(content, cut_all=True) +'''用counter统计词频''' +result = Counter() +for seg in seg_list: + if len(seg) > 1: + result[seg] = result[seg] + 1 +mydic = result.most_common(100) +'''返回一个对象的string格式''' +mystr = str(mydic) + +'''连接服务器,用yagmail发送邮件,此处的password为邮箱的授权码,非邮箱登录密码''' +sendSmpt = yagmail.SMTP(user = input('15001901187@163.com'), +password=getpass.getpass('mogudidizi'),host='smtp.163.com') +sendSmpt.send(to = input('pythoncamp@163.com'),subject="191010072 Bear4",contents=mystr) \ No newline at end of file From 23aec562f2ef2aab4390048ff4e84287b37c77a7 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Tue, 3 Dec 2019 00:17:25 +0800 Subject: [PATCH 36/39] Update stats_word.py --- exercises/1901010072/d11/mymodule/stats_word.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/1901010072/d11/mymodule/stats_word.py b/exercises/1901010072/d11/mymodule/stats_word.py index 7dc9790e2..47ab87728 100644 --- a/exercises/1901010072/d11/mymodule/stats_word.py +++ b/exercises/1901010072/d11/mymodule/stats_word.py @@ -29,4 +29,4 @@ '''连接服务器,用yagmail发送邮件,此处的password为邮箱的授权码,非邮箱登录密码''' sendSmpt = yagmail.SMTP(user = input('15001901187@163.com'), password=getpass.getpass('mogudidizi'),host='smtp.163.com') -sendSmpt.send(to = input('pythoncamp@163.com'),subject="191010072 Bear4",contents=mystr) \ No newline at end of file +sendSmpt.send(to = input('pythoncamp@163.com'),subject="191010072 Bear127",contents=mystr) \ No newline at end of file From 1754820a35a0cc84af6450b5777b15127aea1a60 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Wed, 4 Dec 2019 23:55:49 +0800 Subject: [PATCH 37/39] Update main.py.py --- exercises/1901010072/d11/main.py.py | 57 ++++++++++++----------------- 1 file changed, 23 insertions(+), 34 deletions(-) diff --git a/exercises/1901010072/d11/main.py.py b/exercises/1901010072/d11/main.py.py index 4cf980dcc..3f9ce7402 100644 --- a/exercises/1901010072/d11/main.py.py +++ b/exercises/1901010072/d11/main.py.py @@ -1,45 +1,34 @@ from mymodule import stats_word -from os import path -import json -import re +import yagmail +import requests +import pyquery +import getpass import logging -logging.basicConfig(format='file:%(filename)s|line:%(lineno)d|message:%(message)s',level=logging.DEBUG) - -def load_file(): - ''' - 1. - 下面是常用的获取文件路径的方式,要确保tang300.json跟当前文件在同一个文件夹下,这两种方式等价 - file_path=path.join(path.dirname(path.abspath(_file_)),'./tang300.json') - ''' - file_path=path.join(path.dirname(path.abspath(__file__)),'tang300.json') - print('当前文件路径:',__file__,'\n读取文件路径:',file_path) - ''' - 2. - 这种方式表示tang300.json在当前文件的上一级目录 - file_path=path.join(path.dirname(path.abspath(__file)),'../tang300.json') - print(__file__,file_path) +#安装依赖包 requests yagmail pyquery lxml +#pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests yagmail pyquery lxml - 3. - 这种方式表示tang300.json在当前文件的上一级目录的data文件夹下 - file_path=path.join(path.dirname(path.abspath(__file__)),'../data/tang300.json') - print(__file__,file_path) - ''' - with open(file_path,'r',encoding='utf-8')as f: - return f.read() +logging.basicConfig(format='file:%(filename)s|line:%(lineno)d|message:%(message)s',level=logging.DEBUG) -def merge_poems(data): - poems='' - for item in data: - poems += item.get('contents','') - return poems +#提取微信公众号文章正文 +def get_article(): + r=requests.get('https://mp.weixin.qq.com/s/hT45I5TsNv18AAfNsx81PA') + document=pyquery.PyQuery(r.text) + return document('#js_content').text() def main(): try: - data=load_file() - #logging.info(data) - poems=merge_poems(json.loads(data)) - logging.info('result==>%s',stats_word.stats_text_cn(poems,100)) + article=get_article() + result= stats_word.stats_text_cn(article,10) + logging.info('%s %s',type(result),str(result)) + sender=input('请输入发件人邮箱:') + #为了保护密码,输入密码的时候不会显示出来,直接输入,完成后按回车就行 + password=getpass.getpass('输入发件人邮箱密码:') + recipients=input('请输入收件人邮箱:') + #如果使用的是QQ邮箱这里就填 smtp.qq.com + yag=yagmail.SMTP(sender,password,'smtp.163.com') + yag.send(recipients,'自学训练学习2群 190101***',str(result)) + logging.info("已发送,请注意查收.") except Exception as e: logging.exception(e) From a74e80a9a13c3f9bdbc007aa987d98beefcc6169 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Wed, 4 Dec 2019 23:55:52 +0800 Subject: [PATCH 38/39] Create stats_word.py --- .../1901010072/d12/mymodule/stats_word.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 exercises/1901010072/d12/mymodule/stats_word.py diff --git a/exercises/1901010072/d12/mymodule/stats_word.py b/exercises/1901010072/d12/mymodule/stats_word.py new file mode 100644 index 000000000..47ab87728 --- /dev/null +++ b/exercises/1901010072/d12/mymodule/stats_word.py @@ -0,0 +1,32 @@ +import requests +from pyquery import PyQuery +import re +import jieba +from collections import Counter +import getpass +import yagmail + +'''获取目标目标网页内容,类型是一个HTTP''' +response=requests.get("https://mp.weixin.qq.com/s/pLmuGoc4bZrMNl7MSoWgiA") +'''提取http文件中p之间的内容''' +document = PyQuery(response.text) +content = document('p').text() + + +'''用正则去掉文本中的数字,字母和符号''' +content = re.sub('[a-zA-Z0-9’!"%&\'^\s+|\s+$()*+,-./:;,。?、…?“”‘’!]+',"",content) +'''用jieba将文本进行全模式切分''' +seg_list = jieba.cut(content, cut_all=True) +'''用counter统计词频''' +result = Counter() +for seg in seg_list: + if len(seg) > 1: + result[seg] = result[seg] + 1 +mydic = result.most_common(100) +'''返回一个对象的string格式''' +mystr = str(mydic) + +'''连接服务器,用yagmail发送邮件,此处的password为邮箱的授权码,非邮箱登录密码''' +sendSmpt = yagmail.SMTP(user = input('15001901187@163.com'), +password=getpass.getpass('mogudidizi'),host='smtp.163.com') +sendSmpt.send(to = input('pythoncamp@163.com'),subject="191010072 Bear127",contents=mystr) \ No newline at end of file From 73d523873b8313d72f4993e47df8165746df4af5 Mon Sep 17 00:00:00 2001 From: Bear127 <48996947+Bear127@users.noreply.github.com> Date: Wed, 4 Dec 2019 23:55:55 +0800 Subject: [PATCH 39/39] Create main.py.py --- exercises/1901010072/d12/main.py.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 exercises/1901010072/d12/main.py.py diff --git a/exercises/1901010072/d12/main.py.py b/exercises/1901010072/d12/main.py.py new file mode 100644 index 000000000..01d0cf17e --- /dev/null +++ b/exercises/1901010072/d12/main.py.py @@ -0,0 +1,23 @@ +from mymodule import stats_word +from pyquery import PyQuery +from wxpy import * +import getpass +import requests + +bot = Bot() +my_friend = bot.friends() +#my_friend = bot.friends().search("丽")[0] +#my_friend.send("请发一篇公众号文章给我,我想给些惊喜你看,返回文章前10个高频词给你") +#print("消息发送成功") + +@bot.register(my_friend) +def send_result(msg): + if msg.type == "Sharing": + response = requests.get(msg.url) + document = PyQuery(response.text) + content = document('#js_content').text() + str1 = str(dict(stats_word.stats_text_cn(content,10))) + print(str1) + #my_friend.send(str1) + +embed() \ No newline at end of file