Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions exercises/1901100351/d08/mymodule/main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
# 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 = '''
愚公移山
Expand All @@ -20,7 +45,7 @@
二山的守護神被愚公的堅毅精神嚇倒,便把此事奏知天帝。天帝佩服愚公的精神,就命
兩位大力神揹走二山。

17**2


How The Foolish Old Man Moved Mountains
Yugong was a ninety-year-old man who lived at the north
Expand Down Expand Up @@ -59,4 +84,5 @@
try:
print('合并词频统计结果:', stats_word.stats_text(text))
except ValueError:
print()
print()

68 changes: 35 additions & 33 deletions exercises/1901100351/d08/mymodule/stats_word.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,51 @@
# 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)#创建无序不重复集合

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 = '''
Expand Down
64 changes: 64 additions & 0 deletions exercises/1901100351/d09/mymodule/main.py
Original file line number Diff line number Diff line change
@@ -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.
'''
93 changes: 93 additions & 0 deletions exercises/1901100351/d09/mymodule/stats_word.py
Original file line number Diff line number Diff line change
@@ -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 之父
做也许好过不做,但不假思索就动手还不如不做
如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然
命名空间是一种绝妙的理念,请多加利用
'''