Python正则表达式

Python正则表达式

1. 主要作用

在某个大文本里搜索需要的字段

2.所需文本

poem.txt

Very quietly I take my leave

As quietly as I came here;

Quietly I wave good-bye

To the rosy clouds in the western sky.

The golden willows by the riverside

Are young brides in the setting sun;

Their reflections on the shimmering waves

Always linger in the depth of my heart.

The floating heart growing in the sludge

Sways leisurely under the water;

In the gentle waves of Cambridge

I would be a water plant!

That pool under the shade of elm trees

Holds not water but the rainbow from the sky;

Shattered to pieces among the duckweeds

Is the sediment of a rainbow-like dream?

To seek a dream? Just to pole a boat upstream

To where the green grass is more verdant;

Or to have the boat fully loaded with starlight

And sing aloud in the splendour of starlight.

But I cannot sing aloud

Quietness is my farewell music;

Even summer insects help silence for me

Silent is Cambridge tonight!

Very quietly I take my leave

As quietly as I came here;

Gently I flick my sleeves

Not even a wisp of cloud will I bring away

3.代码实现

1.导入re库

import re

2.导入文件

text = ""
file = open("poem.txt")
for line in file:
    text=text+line
file.close()

3.文本操作

  • 在text中找所有的“to”

    result = re.findall("to",text)
    print result
    
  • 以后根据需求补充

4. 其他注意

  • 正则表达式不仅能处理字符串数据也可以处理数值数据

你可能感兴趣的:(Python正则表达式)