Python笔记【 飞桨、百度领航团 、零基础Python】2021-02-08

Python笔记【 飞桨、百度领航团 、零基础Python】2021-02-08

课程链接:https://aistudio.baidu.com/aistudio/course/introduce/7073

第一天笔记

 

 

 

注释#     , ’’’   , """

 

  1. Python中的小括号():
    代表tuple元祖数据类型,元祖是一种不可变序列。创建方法很简单,大多数时候都是小括号括起来的。
  2. 中括号[]:
    代表list列表数据类型,列表是一种可变序列。创建方法既简单又特别。

 

 

  1. 花括号{}:
    代表dict字典数据类型,字典是Python中唯一内建的映射类型。字典中的值没有特殊的顺序,但都是存储在一个特定的键(key)下。键可以是数字、字符串甚至是元组。

 

在Python中,有两种情况下可以省略括号。
将生成器作为函数的唯一参数
元组作为字典的键

       

    

如果希望在中间离开循环,也就是 f or 循环结束重复之前,或者 while 循环找到结束条件之 前。有两种式来做到

  • 使⽤ break 语句来完全终⽌循环。
  • 使⽤ continue 语句直接跳到循环的下⼀次迭代。

    

99乘法表左下角

方式一:通过【for..in..】方法实现

for i in range(9,0,-1): #参数:计数从9开始,0结束,步长-1

    for j in range(1,i+1):

         print("%d*%d=%2d"%(j,i,j*i),end=' ')

    print("")

 

#方式二:通过【while】方法实现

i=9

while i>=1:

    j = 1

    while j<=i:

        print("%d*%d=%2d"%(j,i,j*i),end=' ')

        j+=1

    print("")

i-=1

右上角

for i in range(9,0,-1):
    for j in range(1,i+1):
         print("%d*%d=%2d"%(j,i,j*i),end=' ')
    print("")
    for k in range(i,10):
         print(end='  
 
 
 
 

2. 输入两个整数,如果两个整数之和小于100,则输出 '小于100',否则输出 '不小于100'

a = input('请输入第一个整数: ')

print(a)

b = input('请输入第二个整数: ')

print(b)

分别把 a转换成整数

a = int(a)

b = int(b)

 

计算 a的和,赋值给变量c

c=int(a+b)

 

判断c是否小于100,按要求输出

if c > 100:

 print('c=',c)

elseprint('不小于100')

输入两组姓名和年龄,然后存入一个字典,并输出

name1 = input('请输入第一个姓名: ')

age1= input('请输入第一个年龄: ')

name2 = input('请输入第二个姓名: ')

age2 = input('请输入第二个年龄: ')

 

# 分别把age1age2转成整数

age1= int(input('请输入第一个年龄: '))

print(age1)

age2 = int(input('请输入第二个年龄: '))

print(age2)

# 构造字典dict_name

dict_name = { 'name1':'小李','name2':'小张'}

 

# 打印字典

print(dict_name)

依次输入10组整数,然后求和,并输出

sum_num = 0

for i in range(10):

    # input输入数字并转化为整数

    print('',i+1,'')

    sum_num1 = int(input('请输入输入数字:'))

    print(sum_num1)

 

    # sum_num 对输入的数字进行累加

    sum_num = sum_num1 + sum_num

print('求和结果为',sum_num)

 

第二天笔记

 

 选取列表的第2到第5项,并打印(从0开始计数,即取出c d e f

# 选取第2-5项,并打印

for i in range(len(words)):

    if i < 5 and i >0:

        print (words[i])

else: pass

使用列表生成式的方法,根据 list1 生成 list2

list1 = [1, 2, 3, 4, 5, 6, 7, 8] # 根据list1生成list2

list2 = [100, 200, 300, 400, 500, 600, 700, 800]


list1 = [1, 2, 3, 4, 5, 6, 7, 8]

list2 = []

list3 = []

# 列表推导式生成list2

for i in range(len(list1)):

    list3.append(list1[i]*100)

    i = list1[i]*100

    list2.append(i)

print(list2)

print(list3)

把下列字符串按下划线('_')划分成若干个片段


string1 = 'this_is_a_sample'

 

# '_'划分string1

string1.split('_')

['this', 'is', 'a', 'sample']

 

string = 'Hello_world!'

        # 01234567891011

print(string[2])

print(string[2:5])#左开右闭

print(string[3:])#3至右取完

print(string[8:2:-1])#8至左2,步长为-1(向左)

 

# 如果字符串以'p'结尾,则打印

list_string = ['apple','banana_p','orange','cherry_p']

for fruit in list_string:

    if fruit[-1] == 'p':#(右数末尾)

        print(fruit)

 

# 如果字符串以'pr'结尾,则打印

list_string = ['apple','banana_pr','orange','cherry_pr']

for fruit in list_string:

    if fruit.endswith('pr'):

        print(fruit)

 

my_string = 'hello_world'

print(my_string.upper())#小写转大写

print(my_string.lower())#大写转小

print(my_string.capitalize())#首字母大写

 

HELLO_WORLD

hello_world

Hello_world

 

%表示输入,当字符串很长需换行好看,用\链接

 

第三天笔记函数

https://aistudio.baidu.com/aistudio/projectdetail/1521571

统计英语6级试题中所有单词的词频,并返回一个如下样式的字典

{'and':100,'abandon':5}

英语6级试题的文件路径./artical.txt

原文如下

Passage One

 

Questions 46 to 50 are based on the following passage.

 

Last year, a child was born at a hospital in the UK with her heart outside her body. Few babies survive this rare condition, and those who do must endure numerous operations and are likely to have complex needs. When her mother was interviewed, three weeks after her daughter's birth, she was asked if she was prepared for what might be a daunting task caring for her. She answered without hesitation that, as far as she was concerned, this would be a "privilege".

 

Rarely has there been a better example of the power of attitude, one of our most powerful psychological tools. Our attitudes allow us to turn mistakes into opportunities, and loss into the chance for new beginnings. An attitude is a settled way of thinking, feeling and/or behaving towards particular objects, people, events or ideologies. We use our attitudes to filter, interpret and react to the world around us. You weren't born with attitudes, rather they are all learned, and this happens in a number of ways.

 

The most powerful influences occur during early childhood and include both what happened to you directly, and what those around you did and said in your presence. As you acquire a distinctive identity, your attitudes are further refined by the behavior of those with whom you identify -- your family, those of your gender and culture, and the people you admire, even though you may not know them personally. Friendships and other important relationships become increasingly important, particularly during adolescence. About that same time and throughout adulthood, the information you receive, especially when ideas are repeated in association with goals and achievements you find attractive, also refines your attitudes.

 

Many people assume that our attitudes are internally consistent, that is, the way you think and feel about someone or something predicts your behavior towards them. However, may studies have found that feelings and thoughts don't necessarily predict behavior. In general, your attitudes will be internally consistent only when the behavior is easy, and when those around you hold similar beliefs. That's why, for example, may say they believe in the benefits of recycling or exercise, but don't behave in line with their views, because it takes awareness, effort and courage to go beyond merely stating that you believe something is a good idea.

 

One of the most effective ways to change an attitude is to start behaving as if you already feel and think the way you'd prefer to. Take some time to reflect on your attitudes, to think about what you believe and why. Is there anything you consider a burden rather than a privilege? It so, start behaving -- right now -- as if the latter is the case.

 

46. What do we learn from the passage about attitude?

A) It shapes our beliefs and ideologies.

B) It improves our psychological wellbeing.

C) It determines how we respond to our immediate environment.

D) It changes the way we think, feel and interact with one another.

47. What can contribute to the refinement of one's attitude, according to the passage?

A) Their idols' behaviors.

B) Their educational level.

C) Their contact with the opposite gender.

D) Their interaction with different cultures.

48. What do many studies find about people's feelings and thoughts?

A) They may not suggest how a person is going to behave.

B) They are in a way consistent with a person's mentality.

C) They may not find expression in interpersonal relations.

D) They are in line with a person's behavior no matter what.

49. How come many people don't do what they believe is good?

A) They can't afford the time.

B) They have no idea how to.

C) They are hypocritical.

D) They lack willpower.

50. What is proposed as a strategy to change attitude?

A) Changing things that require one's immediate attention.

B) Starting to act in a way that embodies one's aspirations.

C) Adjusting one 's behavior gradually over a period of time.

D) Considering ways of reducing one's psychological burdens.

 

Passage Two

 

Questions 51 to 55 are based on the following passage.

 

Industrial fishing for krill in the unspoilt waters around Antarctica is threatening the future of one of the world's last great wildernesses, according to a new report.

 

The study by Greenpeace analysed the movements of krill fishing vessels in the region and found they were increasingly operating "in the immediate vicinity of penguin colonies and whale feeding grounds". It also highlights incidents of fishing boats being involved in groundings, oil spills and accidents, which posed a serious threat to the Antarctic ecosystem.

 

The report, published on Tuesday, comes amid growing concern about the impact of fishing. and climate change on the Antarctic. A global campaign has been launched to create a network of ocean sanctuaries to protect the seas in the region and Greenpeace is calling for an immediate halt to fishing in areas being considered for sanctuary status.

 

Frida Bengtsson from Greenpeace's Protect the Antarctic campaign said: "If the krill industry wants to show it's a responsible player, then it should be voluntarily getting out of any area which is being proposed as an ocean sanctuary, and should instead be backing the protection of these huge tracts of the Antarctic."

 

A global campaign has been launched to turn a huge tract of Antarctic seas into ocean sanctuaries, protecting wildlife and banning not just krill fishing, but all fishing. One was created in the Ross Sea in 2016, another reserve is being proposed in a vast area of the Weddell Sea, and a third sanctuary is under consideration in the area west of the Antarctic Peninsula -- a key krill fishing area.

 

The Commission for the Conservation of Antarctic Marine Living Resources (CCAMLR) manages the seas around Antarctica. It will decide on the Weddell Sea sanctuary proposal at a conference in Australia in October, although a decision on the peninsula sanctuary is not expected until later.

 

Keith Reid, a science manager at CCAMLR, said that the organisation sought "a balance between protection, conservation and sustainable fishing in the Southern Ocean." He said although more fishing was taking place nearer penguin colonies it was often happening later in the season when these colonies were empty.

 

"The creation of a system of marine protected areas is a key part of ongoing scientific and policy discussions in CCAMLR," he added. "Our long-term operation in the region depends on a healthy and thriving Antarctic marine ecosystem, which is why we have always had an open dialogue with the environmental non-governmental organisations. We strongly intend to continue this dialogue, including talks with Greenpeace, to discuss improvements based on the latest scientific data. We are not the ones to decide on the establishment of marine protected areas, but we hope to contribute positively with our knowledge and experience."

 

51. What does Greenpeace's study find about krill fishing?

A) It caused a great many penguins and whales to migrate.

B) It was depriving penguins and whales of their habitats.

C) It was carried out too close to the habitats of penguins and whales.

D) It posed an unprecedented threat to the wildlife around Antarctica.

52. For what purpose has a global campaign been launched?

A) To reduce the impact of climate change on Antarctica.

B) To establish conservation areas in the Antarctic region.

C) To regulate krill fishing operations in the Antarctic seas.

D) To publicise the concern about the impact of krill fishing.

53. What is Greenpeace's recommendation to the krill industry?

A) Opting to operate away from the suggested conservation areas.

B) Volunteering to protect the endangered species in the Antarctic.

C) Refraining from krill fishing throughout the breeding season.

D) Showing its sense of responsibility by leading the global campaign.

54. What did CCAMLR aim to do according to its science manager?

A) Raise public awareness of the vulnerability of Antarctic species.

B) Ban all commercial fishing operations in the Southern Ocean.

C) Keep the penguin colonies from all fishing interference.

D) Sustain fishing without damaging the Antarctic ecosystem.

55. How does CCAMLR define its role in the conservation of the Antarctic environment?

A) A coordinator in policy discussions.

B) An authority on big data analysis.

C) A provider of the needed expertise.

D) An initiator of marine sanctuaries.

 

Passage One

 

Questions 46 to 50 are based on the following passage.

 

Schools are not just a microcosm of society; they mediate it too. The best seek to alleviate the external pressures on their pupils while equipping them better to understand and handle the world outside -- at once sheltering them and broadening their horizons. This is ambitious in any circumstances, and in a divided and unequal society the two ideals can clash outright.

 

Trips that many adults would consider the adventure of a lifetime -- treks in Bomeo, a sports tour to Barbados -- appear to have become almost routine at some state schools. Parents are being asked for thousands of pounds. Though schools cannot profit from these trips, the companies that arrange them do. Meanwhile, pupils arrive at school hungry because their families can't afford breakfast. The Child Poverty Action Group says nine out of 30 in every classroom fall below the poverty line. The discrepancy is startlingly apparent. Introducing a fundraising requirement for students does not help, as better-off children can tap up richer aunts and neighbours.

 

Probing the rock pools of a local beach or practising French on a language exchange can fire children's passions, boost their skills and open their eyes to life 's possibilities. Educational outings help bright but disadvantaged students to get better scores in A-level tests. In this globalised age, there is a good case for international travel, and some parents say they can manage the cost of a school trip abroad more easily than a family holiday. Even in the face of immense and mounting financial pressures, some schools have shown remarkable determination and ingenuity in ensuring that all their pupils are able to take up opportunities that may be truly life-changing. They should be applauded. Methods such as whole-school fundraising, with the proceeds pooled, can help to extend opportunities and fuel community spirit.

 

But 3,000 pounds trips cannot be justified when the average income for families with children is just over 30,000 pounds. Such initiatives close doors for many pupils. Some parents pull their children out of school because of expensive field trips. Even parents who can see that a trip is little more than a party or celebration may well feel guilt that their child is left behind.

 

The Department for Education 's guidance says schools can charge only for board and lodging if the trip is part of the syllabus, and that students receiving government aid are exempt from these costs. However, many schools seem to ignore the advice; and it does not cover the kind of glamorous, exotic trips, which are becoming increasingly common. Schools cannot be expected to bring together communities single-handed. But the least we should expect is that they do not foster divisions and exclude those who are already disadvantaged.

 

46. What does the author say best schools should do?

A) Prepare students to both challenge and change the divided unequal society.

B) Protect students from social pressures and enable them to face the world.

C) Motivate students to develop their physical as well as intellectual abilities.

D) Encourage students to be ambitious and help them to achieve their goals.

47. What does the author think about school field trips?

A) They enable students from different backgrounds to mix with each other.

B) They widen the gap between privileged and disadvantaged students.

C) They give the disadvantaged students a chance to see the world.

D) They only benefit students with rich relatives and neighbours.

48. What does the author suggest can help build community spirit?

A) Events aiming to improve community services.

B) Activities that help to fuel students' ingenuity.

C) Events that require mutual understanding,

D) Activities involving all students on campus.

49. What do we learn about low-income parents regarding school field trips?

A) They want their children to participate even though they don't see much benefit.

B) They don't want their kids to participate but find it hard to keep them from going.

C) They don't want their kids to miss any chance to broaden their horizons despite the cost.

D) They want their children to experience adventures but they don't want them to run risks.

50. What is the author's expectation of schools?

A) Bringing a community together with ingenuity.

B) Resolving the existing discrepancies in society.

C) Avoiding creating new gaps among students.

D) Giving poor students preferential treatment.

 

Passage Two

 

Questions 51 to 55 are based on the following passage.

 

Rising temperatures and overfishing in the pristine waters around the Antarctic could see king penguin populations pushed to the brink of extinction by the end of the century, according to a new study. The study's report states that as global warming transforms the environment in the world's last great wilderness, 70 percent of king penguins could either disappear or be forced to find new breeding grounds.

 

Co-author Celine Le Bohec, from the University of Strasbourg in France, warned: "If there're no actions aimed at halting or controlling global warming, and the pace of the current human-induced changes such as climate change and overfishing stays the same, the species may soon disappear." The findings come amid growing concern over the future of the Antarctic. Earlier this month a separate study found that a combination of climate change and industrial fishing is threatening the krill population in Antarctic waters, with a potentially disastrous impact on whales, seals and penguins. But today's report is the starkest warming yet of the potentially devastating impact of climate change and human exploitation on the Antarctic's delicate ecosystems.

 

Le Bohec said: "Unless current greenhouse gas emissions drop, 70 percent of king penguins -- 1.1 million breeding pairs -- will be forced to relocate their breeding grounds, or face extinction by 2100." King penguins are the second-largest type of penguin and only breed on specific isolated islands in the Southern Ocean where there is no ice cover and easy access to the sea. As the ocean warms, a body of water called the Antarctic Polar Front -- an upward movement of nutrient-rich sea that supports a huge abundance of marine life -- is being pushed further south. This means that king penguins, which feed on fish and kill in this body of water, have to travel further to their feeding grounds, leaving their hungry chicks for longer. And as the distance between their breeding, grounds and their fool prows, entire colonies could be wiped out.

 

Le Bohec said: "The plight of the king penguin should serve as a warming about the future of the entire marine environment in the Antarctic. Penguins, like other seabirds and marine mammals, occupy higher levels in the food chain and they are what we call bio-indicators of their ecosystems." Penguins are sensitive indicators of changes in marine ecosystems. As such, they are key species for understanding and predicting impacts of global change on Antarctic and sub-Antarctic marine ecosystems. The report found that although some king penguins may be able to relocate to new breeding grounds closer to their retreating food source, suitable new habitats would be scarce. Only a handful of islands in the Southern Ocean are suitable for sustaining large breeding colonies.

 

51. What will happen by 2100, according to a new study?

A) King penguins in the Antarctic will be on the verge of dying out.

B) Sea water will rise to a much higher level around the Antarctic.

C) The melting ice cover will destroy the great Antarctic wilderness.

D) The pristine waters around the Antarctic will disappear forever.

52. What do we learn from the findings of a separate study?

A) Shrinking krill population and rising temperatures could force Antarctic whales to migrate.

B) Human activities have accelerated climate change in the Antarctic region in recent years.

C) Industrial fishing and climate change could be fatal to certain Antarctic species.

D) Krill fishing in the Antarctic has worsened the pollution of the pristine waters.

53. What does the passage say about king penguins?

A) They will turn out to be the second-largest species of birds to become extinct.

B) Many of them will have to migrate to isolated islands in the Southern Ocean.

C) They feed primarily on only a few kinds of krill in the Antarctic Polar Front.

D) The majority of them may have to find new breeding grounds in the future.

54. What happens when sea levels rise in the Antarctic?

A) Many baby king penguins can't have food in time.

B) Many king penguins could no longer live on kill.

C) Whales will invade king penguins' breeding grounds.

D) Whales will have to travel long distances to find food.

55. What do we learn about the Southern Ocean?

A) The king penguins there are reluctant to leave for new breeding grounds.

B) Its conservation is key to the sustainable propagation of Antarctic species.

C) It is most likely to become the ultimate retreat for species like the king penguin.

D) Only a few of its islands can serve as luge breeding grounds for king penguins.

 

处理要求

  • (a) '\n'是换行符 需要删除
  • (b) 标点符号需要处理

['.', ',', '!', '?', ';', '\'', '\"', '/', '-', '(', ')']

  • (c) 阿拉伯数字需要处理

['1','2','3','4','5','6','7','8','9','0']

  • (d) 注意大小写 一些单词由于在句首,首字母大写了。需要把所有的单词转成小写

'String'.lower()

  • (e) 高分项

通过自己查找资料学习正则表达式,并在代码中使用(re模块)

可参考资料:https://docs.python.org/3.7/library/re.html

 

import re

# 读取文件

def get_artical(artical_path):

    with open(artical_path) as fr:

        data = fr.read()

    return data

 

#处理函数

def handle(data):   

    counts = {}

    data1 = re.sub('\n',' ',data)#替换换行符为空格

    reg = "[^A-Za-z\']"

    data = re.sub(reg,' ',data1)#保留字母

    data = data.lower()#转为小写字母

    list_data = data.split()

    #遍历统计

    for word in list_data:

        if word in counts.keys():

            counts[word] = counts[word] +1

        else:

            counts[word] = 1

    return counts

 

#主程序

data = get_artical('./artical.txt')

re_counts1 = handle(data)

print(re_counts1)

print("按照词频从高到低排序如下")

re_counts2 = sorted(re_counts1.items(),key=lambda x:x[1],reverse=True)#将字典转为元组后,再按词频从高到低排序,

print(re_counts2)

已经被删减

{'passage': 11, 'one': 8, 'questions': 4, 'to': 95, 'are': 25, 'based': 5, 'on': 25, 'the': 169, 'following': 4, 'last': 3, 'year': 1, 'a': 87, 'child': 3, 'was': 10, 'born': 2, 'at': 7, 'hospital': 1, 'in': 61, 'uk': 1, 'with': 19, 'her': 5, 'heart': 1, 'outside': 2, 'body': 3, 'few': 3, 'babies': 1, 'survive': 1, 'this': 9, 'rare': 1, }]

按照词频从高到低排序如下

[('the', 169), ('to', 95), ('a', 87), ('of', 82), ('and', 74), ('in', 61), ('is', 34), ('antarctic', 32), ('they', 30), ('their', 28), ('are', 25), ('on', 25), ('what', 25), ('that', 24), ('for', 22), ('b', 20), ('c', 20), ('d', 20), ('fishing', 20), ('with', 19), ('be', 18), ('as', 18), ('it', 18), ('penguins', 17), ('you', 15), ('king', 15), ('krill', 14), ('students', 14), ('we', 13), ('about', 13), ('have', 12), ('will', 12), ('from', 12), ('passage', 11), ('do', 11), ('them', 11), ('change', 11), ('breeding', )]

 

猜你喜欢

转载自blog.csdn.net/weixin_45944918/article/details/113757526