51、Python基础与正则表达式入门

Python基础与正则表达式入门

1. Python日期处理

Python提供了丰富的日期相关函数,相关文档可参考:http://docs.python.org/2/library/datetime.html 。

以下是一个示例脚本 Datetime2.py ,用于显示各种与日期相关的值:

import time
import datetime
print("Time in seconds since the epoch: %s" %time.time())
print("Current date and time: " , datetime.datetime.now())
print("Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M"))
print("Current year: ", datetime.date.today().strftime("%Y"))
print("Month of year: ", datetime.date.today().strftime("%B"))
print("Week number of the year: ", datetime.date.today().strftime("%W"))
print("Weekday of the week: ", datetime.date.today().strftime("%w"))
print("Day of year: ", datetime.date.today().strftime("%j"))
print("Day of the month : ", datetime.date.today().strftime("%d"))
print("Day of week: ", datetime.date.today().strftime("%A"))

运行上述代码的输出示例如下:

Time in seconds since the epoch: 1375144195.66
Current date and time:  2013-07-29 17:29:55.664164
Or like this:  13-07-29-17-29
Current year:  2013
Month of year:  July
Week number of the year:  30
Weekday of the week:  1
Day of year:  210
Day of the month :  29
Day of week:  Monday

Python还支持对日期相关值进行算术计算,示例代码如下:

from datetime import timedelta 
a = timedelta(days=2, hours=6) 
b = timedelta(hours=4.5)
c = a + b
print(c.days)
print(c.seconds)
print(c.seconds / 3600)
print(c.total_seconds() / 3600)

输出结果为:

2
37800
10.5
58.5

另外,还可以将字符串转换为日期,并计算两个日期之间的差值,示例代码 String2Date.py 如下:

from datetime import datetime
text = '2014-08-13'
y = datetime.strptime(text, '%Y-%m-%d')
z = datetime.now()
diff = z - y
print('Date difference:',diff)

输出示例:

Date difference: -210 days, 18:58:40.197130
2. Python异常处理

在Python中,不能像JavaScript那样将数字和字符串相加。不过,可以使用 try/except 结构来检测非法操作,这与JavaScript和Java中的 try/catch 结构类似。

以下是一个 try/except 块的示例:

try:
    x = 4
    y = 'abc'
    z = x + y
except:
    print('cannot add incompatible types:', x, y)

运行上述代码时,由于变量 x y 类型不兼容, except 代码块中的 print 语句将被执行。

减法操作中,如果对两个字符串进行减法运算会抛出异常,例如:

>>> 'a' - 'b'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’

可以使用 try/except 块来处理这种情况:

try:
    print('a' - 'b')
except TypeError:
    print('TypeError exception while trying to subtract two strings')
except:
    print('Exception while trying to subtract two strings')

输出结果为:

TypeError exception while trying to subtract two strings

以下是一个更复杂的异常处理示例 Exception1.py

import sys
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as err:
    print("I/O error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

该代码包含一个 try 块和三个 except 语句。如果 try 块中出现错误,会依次与各个 except 语句进行匹配,若匹配成功则执行相应的 print 语句并终止程序;若都不匹配,则由最后一个 except 语句处理异常。

也可以在一个语句中指定多个异常类型,例如:

except (NameError, RuntimeError, TypeError):
    print('One of three error types occurred')
3. 处理用户输入

Python可以通过 input() 函数或 raw_input() 函数从命令行读取用户输入。通常将用户输入赋值给一个变量,用户按下 <return> 键时输入结束。

以下是一个简单的示例 UserInput1.py

userInput = input("Enter your name: ")
print ("Hello %s, my name is Python" % userInput)

假设用户输入 Dave ,输出结果为:

Hello Dave, my name is Python

用户输入可能会引发异常,因此需要包含异常处理代码。以下是一个尝试将用户输入的字符串转换为数字的示例 UserInput2.py

userInput = input("Enter something: ")
try:
    x = 0 + eval(userInput)
    print('you entered the number:',userInput)
except:
    print(userInput,'is a string')

该代码使用了 eval() 函数,不过应避免使用该函数,以免代码执行任意(可能具有破坏性)的命令。

以下是一个计算用户输入的两个数字之和的示例 UserInput3.py

sum = 0
msg = 'Enter a number:'
val1 = input(msg)
try:
    sum = sum + eval(val1)
except:
    print(val1,'is a string')
msg = 'Enter a number:'
val2 = input(msg)
try:
    sum = sum + eval(val2)
except:
    print(val2,'is a string')
print('The sum of',val1,'and',val2,'is',sum)
4. Python与表情符号处理

以下是一个移除文本字符串中表情符号的示例 remove_emojis.py

import re
import emoji
text = "I want a Chicago deep dish pizza tonight \U0001f600"
print("text:")
print(text)
print()
emoji_pattern = re.compile("[" "\U0001F1E0-\U0001F6FF" "]+", flags=re.UNICODE)
text = emoji_pattern.sub(r"", text)
text = "".join([x for x in text if x not in emoji.UNICODE_EMOJI])
print("text:")
print(text)
print()

运行该代码,输出结果如下:

text:
I want a Chicago deep dish pizza tonight 
text:
I want a Chicago deep dish pizza tonight
5. 命令行参数

Python提供了 getopt 模块来解析命令行选项和参数, sys 模块通过 sys.argv 提供对命令行参数的访问。 sys.argv 是命令行参数的列表, len(sys.argv) 是命令行参数的数量, sys.argv[0] 是程序名称。

以下是一个示例脚本 test.py

#!/usr/bin/python
import sys
print('Number of arguments:',len(sys.argv),'arguments')
print('Argument List:', str(sys.argv))

运行命令 python test.py arg1 arg2 arg3 ,输出结果为:

Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

还可以使用命令行参数指定Python类中的方法来执行,例如:

python MyClass add 3 5
python MyClass subtract 3 5

以下是一个使用 sys.argv 检查命令行参数数量的示例 Hello.py

import sys
def main():
    if len(sys.argv) >= 2:
        name = sys.argv[1]
    else:
        name = 'World'
    print('Hello', name)
# Standard boilerplate to invoke the main() function
if __name__ == '__main__':
    main()
6. 正则表达式简介

正则表达式(Regular Expressions,简称REs、regexes或regex patterns)是Python中非常强大的语言特性,也可用于其他编程语言。它可以用来指定能够匹配字符串特定“部分”的表达式,例如匹配单个字符或数字、电话号码、邮政编码或电子邮件地址等。

Python的 re 模块(在Python 1.5中添加)提供了Perl风格的正则表达式模式。在深入了解 re 模块的方法之前,需要先了解元字符和字符类。

7. Python中的元字符

Python支持一组元字符,大部分与其他脚本语言(如Perl)和编程语言(如JavaScript和Java)中的元字符相同,完整列表如下:
. ^ $ * + ? { } [ ] \ | ( )
各元字符的含义如下:
| 元字符 | 含义 | 示例 |
| ---- | ---- | ---- |
| ? | 匹配0个或1个 | a? 匹配字符串 a ,但不匹配 ab |
| * | 匹配0个或多个 | a* 匹配字符串 aaa ,但不匹配 baa |
| + | 匹配1个或多个 | a+ 匹配 aaa ,但不匹配 baa |
| ^ | 行的开头 | ^[a] 匹配字符串 abc ,但不匹配 bc |
| $ | 行的结尾 | [c]$ 匹配字符串 abc ,但不匹配 cab |
| . | 单个点,匹配任意字符(除换行符) | |

有时需要匹配元字符本身,可以通过两种方式实现:
- 使用反斜杠 \ “转义”其符号含义,例如 \? \* \+ \^ \$ \. 表示字面字符。
- 将元字符列在方括号内,例如 [+?] + ? 视为字面字符。

^ 字符在正则表达式中的含义取决于其位置:
- ^[a-z] 表示以任意小写字母开头的字符串。
- [^a-z] 表示不包含任何小写字母的字符串。
- ^[^a-z] 表示以非小写字母开头的字符串。
- ^[a-z]$ 表示单个小写字母。
- ^[^a-z]$ 表示单个非小写字母的字符(包括数字)。

re.sub() 方法可以从文本字符串中移除字符(包括元字符),例如:

import re
str = "this string has a / and + in it"
str2 = re.sub("[/]+","",str)
print('original:',str)
print('replaced:',str2)

输出结果:

original: this string has a / and + in it
replaced: this string has a  and + in it

以下是一个移除其他元字符的示例 RemoveMetaChars1.py

import re
text1 = "meta characters ? and / and + and ."
text2 = re.sub("[/\.*?=+]+","",text1)
print('text1:',text1)
print('text2:',text2)

正则表达式 [/\.*?=+]+ 表示匹配方括号内的任意元字符(视为字面字符)的一个或多个连续出现。

通过以上内容,我们对Python的日期处理、异常处理、用户输入处理、表情符号处理、命令行参数以及正则表达式有了初步的了解。在实际应用中,可以根据具体需求灵活运用这些知识。

Python基础与正则表达式入门

8. 正则表达式字符类与 re 模块方法

字符类是正则表达式中的重要概念,它允许你指定一组字符,只要匹配其中任意一个字符就算匹配成功。常见的字符类有:
- [abc] :匹配 a b c 中的任意一个字符。
- [a-z] :匹配任意小写字母。
- [A-Z] :匹配任意大写字母。
- [0-9] :匹配任意数字。

下面是一个使用字符类的简单示例:

import re
text = "abc123"
pattern = re.compile("[a-z][0-9]")
result = pattern.findall(text)
print(result)

输出结果:

['c1']

re 模块包含了几个非常有用的方法,以下是一些常见方法的介绍:

8.1 re.match() 方法

re.match() 方法用于从字符串的起始位置开始匹配,如果匹配成功,则返回一个匹配对象;否则返回 None 。示例代码如下:

import re
text = "hello world"
pattern = re.compile("hello")
result = pattern.match(text)
if result:
    print("匹配成功:", result.group())
else:
    print("匹配失败")

输出结果:

匹配成功: hello
8.2 re.search() 方法

re.search() 方法用于在字符串中搜索匹配的模式,只要找到一个匹配的结果就返回匹配对象,若未找到则返回 None 。示例如下:

import re
text = "world hello"
pattern = re.compile("hello")
result = pattern.search(text)
if result:
    print("找到匹配:", result.group())
else:
    print("未找到匹配")

输出结果:

找到匹配: hello
8.3 re.findall() 方法

re.findall() 方法用于在字符串中查找所有匹配的模式,并以列表的形式返回所有匹配的结果。示例代码如下:

import re
text = "abcaabc"
pattern = re.compile("abc")
result = pattern.findall(text)
print("所有匹配结果:", result)

输出结果:

所有匹配结果: ['abc', 'abc']
9. 正则表达式的分组

在正则表达式中,可以使用圆括号 () 来进行分组。分组的作用是将匹配的部分作为一个整体进行处理,并且可以通过索引来获取分组的内容。示例如下:

import re
text = "2024-01-01"
pattern = re.compile("(\d{4})-(\d{2})-(\d{2})")
result = pattern.search(text)
if result:
    print("年:", result.group(1))
    print("月:", result.group(2))
    print("日:", result.group(3))

输出结果:

年: 2024
月: 01
日: 01
10. 正则表达式的替换与分割
10.1 re.sub() 方法

re.sub() 方法用于在字符串中替换匹配的模式。其语法为 re.sub(pattern, repl, string, count=0, flags=0) ,其中 pattern 是要匹配的模式, repl 是替换的字符串, string 是要处理的字符串, count 是替换的最大次数(默认为0,表示替换所有匹配的结果)。示例如下:

import re
text = "hello world"
pattern = re.compile("world")
new_text = pattern.sub("Python", text)
print("替换后的字符串:", new_text)

输出结果:

替换后的字符串: hello Python
10.2 re.split() 方法

re.split() 方法用于根据匹配的模式对字符串进行分割,返回分割后的字符串列表。示例代码如下:

import re
text = "apple,banana;cherry"
pattern = re.compile("[,;]")
result = pattern.split(text)
print("分割后的列表:", result)

输出结果:

分割后的列表: ['apple', 'banana', 'cherry']
11. 总结

正则表达式是Python中非常强大的工具,通过元字符、字符类和 re 模块的方法,可以实现复杂的文本匹配、搜索、替换和分割操作。以下是一个简单的流程图,展示了使用正则表达式处理文本的基本流程:

graph TD;
    A[定义正则表达式模式] --> B[编译模式];
    B --> C[选择处理方法(match, search, findall等)];
    C --> D[处理文本字符串];
    D --> E[获取结果];

在实际应用中,需要根据具体的需求选择合适的元字符和方法,同时要注意异常处理,以确保程序的健壮性。对于初学者来说,正则表达式可能会比较复杂,但通过不断的练习和实践,会逐渐掌握其使用技巧。例如,在处理用户输入的文本、数据清洗、日志分析等场景中,正则表达式都能发挥重要的作用。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值