python数据分析基础1

这篇博客介绍了Python数据分析的基础,包括print、字符串操作如split、join、strip、replace和大小写转换,以及模块函数与正则表达式中的元字符和相关函数。此外,还讲解了日期处理、列表和元组的操作,字典的创建与使用,控制流如if-else、for循环和异常处理,以及文件的读写操作。
摘要由CSDN通过智能技术生成

1. print

x=4
y=5
z=x+y
print("Four equals %d"%z)
print("the result is {0:d}".format(z))
# 花括号表示占位,:用来间隔传入的值和它的格式
# d表示以整数形式显示这个数字
a=[1,2,3,4]
b=["first","second","third","fourth"]
c=a+b
print("{0}, {1}, {2}".format(a, b, c))

print ("{0:.3f}".format(8.3/2.7))
print("{0:.1f}".format(8.3/2.7))
print(type(c))
#可以对所有对象调用这个函数,来获得关于 Python如何处理这个对象的更多信息

2.字符串

print("{0:s}".format('I\'m enjoying learning Python.'))
#在字符串中的符号和语法符号会混淆的情况下,可以使用转义符/

print("{0:s}".format("This is a long string. Without the backslash \
it would run off of the page on the right in the text editor and be very \
 difficult to read and edit. By using the backslash you can split the long \
  string into smaller strings on separate lines so that the whole string is easy \
   to view in the text editor."))
#长字符串分成多行,\必须位于每一行的最后一位,但是这种在结果页并没有分行处理
print("{0:s}".format('''You can use triple single quotes 
        for multi-line comment strings.'''))
print("{0:s}".format("""You can also use triple double quotes 
      for multi-line comment strings."""))
#可以直接对结果和命令的字符串进行分行处理

string1 = "This is a "
string2 = "short string."
sentence = string1 + string2
print("{0:s}".format(sentence))
print("{0:s} {1:s}{2:s}".format("She is", "very "*4, "beautiful."))
m = len(sentence)
print("{0:d}".format(m))

2.1 split()

string1 = "My deliverable is due in May"
string1_list1 = string1.split()
#split的后面没有参数,默认分割符号为空格
string1_list2 = string1.split(" ",2)
#设定拆除符号位空格,同时设定了拆除的空格个数为2,即把字符串拆分为三个单独的字符串
print("{0}".format(string1_list1))
print("FIRST PIECE:{0} SECOND PIECE:{1} THIRD PIECE:{2}"\
.format(string1_list2[0], string1_list2[1], string1_list2[2]))

string2="Your,deliverable,is,due,in,June"
string2_list=string2.split(',')
print(string2_list)
print("{0} {1} {2}".format(string2_list[1], string2_list[5],\
                                       string2_list[-1]))

2.2 join()

使用 join 函数将列表中的子字符串组合成一个字符串。join 函数 将一个参数放在 join 前面,表示使用这个字符(或字符串)在子字符串之间进行组合

print("{0}".format(','.join string2_list ))

在这个示例中,附加参数为一个逗号,位于圆括号中。所以 join 函数将子字符串组合成一 个字符串,子字符串之间为逗号。因为列表中有 6 个子字符串,所以子字符串被组合成一个 字符串,子字符串之间有 5 个逗号。新生成的字符串是 Your,deliverable,is,due,in,June

2.3 strip()

使用 strip、lstrip 和 rstrip 函数从字符串两端删除不想要的字 符。这 3 个函数都可以在括号中使用一个附加参数来设定要从字符串两端删除的字符(或 字符串)

#一种删除方法
string3 = " Remove unwanted characters from this string.\t\t    \n"
print("{0:s}".format(string3))
string3_lstrip=string3.lstrip()
#从左侧删除,删除了左边的空格
print ("lstrip:{0:s}".format(string3_lstrip))
string3_rstrip=string3.rstrip()
#从右侧删除,删除了转表符和转行符
print ("rstrip:{0:s}".format(string3_rstrip))
string3_strip=string3.strip()
#从两侧删除
print ("strip:{0:s}".format(string3_strip))

#另一种删除方法
string4 = "$$The unwanted characters have been removed.__---++"
string4_strip = string4.strip('$_-+')
#将这些想要删除的符号作为附加参数就能删除
print("{0:s}".format(string4_strip))

2.4 replace()

string5 = "Let's replace the spaces in this sentence with other characters." 
string5_replace = string5.replace(" ", "!@!") 
#将string5中的空格键替换为!@!
print("Output #32 (with !@!): {0:s}".format(string5_replace)) 

2.5 lower、upper、capitalize

lower 和 upper 函数分别 用来将字符串中的字母转换为小写和大写。capitalize 函数对字符串中的第一个字母应用upper 函数,对其余的字母应用 lower 函数

string6 = "Here's WHAT Happens WHEN You Use lower."
print("{}".format(string6.lower()))
string7 = "Here's what Happens when You Use UPPER."
print("Output #35: {0:s}".format(string7.upper()))
string5 = "here's WHAT Happens WHEN you use Capitalize."
print("Output #36: {0:s}".format(string5.capitalize()))

#对字符串中每一个单词的首字母都进行首字母大写
string5_list = string5.split()
for word in string5_list:
    print("{0:s}".format(word.capitalize()))

3.模块函数与正则表达式

import re

通过导入 re 模块,你可以使用一大波函数和元字符来创建和搜索任意复杂的模式。

3.1元字符

元字符(metacharacter)是正则表达式中具有特殊意义的字符。每个元字符都有特殊意义,它们使正则表达式能够匹配特定的字符串。常用的元字符包括 |、()、[]、.、*、+、?、^、 $ 和 (?P)

3.2 其他函数

re 模块中还包括很多有用的函数,用于创建和搜索特定的模式

import re
# 计算字符串中模式出现的次数
string = "The quick brown fox jumps over the lazy dog."
string_list = string.split()
pattern = re.compile(r"The", re.I)
#re.compile 函数将文本形式的模式编译成为编译后的正则表达式
#re.I 函数确保模式是不区分大小写的,能同时在字符串中匹配“The”和“the”
#原始字 符串标志 r 可以确保 Python 不处理字符串中的转义字符,比如 \、\t 或 \n。这样在进行模式匹配时,字符串中的转义字符和正则表达式中的元字符就不会有意外的冲突。
count = 0
for word in string_list:
    if pattern.search(word):
# re.search 函数将列表中的每个单词与正则表 达式进行比较
        count += 1
        print("{0:d}".format(count))

如果想在屏幕上打印出每个匹配的字符串, 而不是匹配的次数

string = "The quick brown fox jumps over the lazy dog."
string_list = string.split()
pattern = re.compile(r"(?P<match_word>The)", re.I)#</match_word>
# (?P<name>)是一个出现在 re.compile 函数中的元字符
#这个元字符使匹配的字符串可以在后面的程序中通过组名符号 <name> 来引用。在这个示例中,这个组被称为 <match_word>。

for word in string_list:
    if pattern.search(word):
        print("{:s}".format(pattern.search(word).group('match_word')))

re.sub 函数来在文本中用一种模式替换另一种模式

# 使用字母“a”替换字符串中的单词“the”
string = "The quick brown fox jumps over the lazy dog."
string_to_find = r"The"
pattern = re.compile(string_to_find, re.I) 
print("{:s}".format(pattern.sub("a", string)))

4.日期

Python 中包含了 datetime 模块,它提供了非常强大的功能来处理日期和时间。

from datetime import date, time, datetime, timedelta 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值