Python分割字符串

Python拆分字符串教程展示了如何在Python中拆分字符串。

我们可以通过以下方法在Python中拆分字符串:

  • str.split,str.rsplit
  • re.split
  • str.partition,str.rpartition

Python拆分/rsplit方法

split方法根据给定的分隔符参数将字符串分成多个部分。使用可选的第二个参数,我们可以控制字符串被剪切的次数。

str.split([sep[, maxsplit]])

str.split方法返回字符串中的单词列表,由分隔符字符串分隔。

参数是:

  • sepâÈ可选。将字符串分成多个拆分组的字符;默认为空格。
  • maxsplit–可选。拆分次数;默认值为-1,它会拆分所有项目。
   
str.rsplit([sep[, maxsplit]])

str.rsplit返回字符串中的单词列表,由分隔符字符串分隔(从右开始)。

Python拆分示例

在下面的示例中,我们使用前面提到的方法将字符串分割成多个部分。

#!/usr/bin/python

line = "sky, club, cpu, cloud, war, pot, rock, water"

words = line.split(',')
print(words)

words2 = line.split(', ')
print(words2)

words3 = line.split(',')
words4 = [e.strip() for e in words3]
print(words4)

在示例中,我们将以逗号分隔的单词行剪切为单词列表。

words = line.split(',')

字符串被逗号分割;但是,单词有空格。

words2 = line.split(', ')

消除空格的一种方法是在separator参数中包含一个空格字符。

words3 = line.split(',')
words4 = [e.strip() for e in words3]

另一种解决方案是使用strip方法。

$ ./splitting.py 
['sky', ' club', ' cpu', ' cloud', ' war', ' pot', ' rock', ' water']
['sky', 'club', 'cpu', 'cloud', 'war', 'pot', 'rock', 'water']
['sky', 'club', 'cpu', 'cloud', 'war', 'pot', 'rock', 'water']

使用maxsplit参数,我们可以设置将完成多少次拆分。

#!/usr/bin/python

line = "sky, club, cpu, cloud, war, pot, rock, water"

words = line.split(', ', 3)

for word in words:
    print(word)

print('-------------------------')

words2 = line.split(', ', 4)

for word in words2:
    print(word)

剩下的单词组成一个字符串。

$ ./maxsplit.py
sky
club
cpu
cloud, war, pot, rock, water
-------------------------
sky
club
cpu
cloud
war, pot, rock, water

在下一个示例中,我们从字符串的末尾获取单词。

#!/usr/bin/python

line = "sky, club, cpu, cloud, war, pot, rock, water"

words = line.rsplit(', ', 3)[-3:]
print(words)

使用rsplit方法,我们得到最后三个单词。

$ ./split_right.py 
['pot', 'rock', 'water']

Python分割线

str.splitlines方法返回字符串中的行列表,在行边界处断开。除非keepends设置为True,否则结果列表中不包含换行符。

行边界为字符,包括换行\n、回车\r、回车/换行\r\n.

str.splitlines([keepends])

这是一种从文件中快速将行拆分为列表的便捷方法。

#!/usr/bin/python

line = "sky\nclub\ncpu\rcloud\r\nwar\npot\nrock\nwater"

words = line.splitlines()
print(words)

该示例将字符串转换为单词列表。

$ ./split_lines.py
['sky', 'club', 'cpu', 'cloud', 'war', 'pot', 'rock', 'water']

在下一个示例中,我们从文件中读取单词。

sky
cup
blue
bear
rock
pen
chair
lamp
bowl
rock
falcon

我们有一个单词文件。

#!/usr/bin/python

filename = 'words.txt'

with open(filename, 'r') as f:
    
    data = f.read()
    words = data.splitlines()
    
    print(words)

read方法将整个文件读入一个字符串。然后使用split_lines将字符串拆分成行。

$ ./split_lines2.py 
['sky', 'cup', 'blue', 'bear', 'rock', 'pen', 'chair', 'lamp', 'bowl', 'rock', 'falcon']

Python重新拆分

使用re.split,我们可以使用正则表达式拆分字符串。

re.split(pattern, string, maxsplit=0, flags=0)

该方法为我们提供了更强大的字符串切割选项。

#!/usr/bin/python

import re

line = "sky, \nclub, \tcpu; cloud,  \n\n\nwar; pot, rock, water"

words = re.split("[;,]\s+", line)
print(words)

在示例中,我们使用re.spit将字符串吐出到单词列表中。单词可以用逗号或分号和多个空格分隔。

$  ./reg_split.py 
['sky', 'club', 'cpu', 'cloud', 'war', 'pot', 'rock', 'water']

Python词频

在下面的例子中,我们计算词频。

$ wget https://raw.githubusercontent.com/janbodnar/data/main/the-king-james-bible.txt

我们使用钦定版圣经。

#!/usr/bin/python

import collections
import re

filename = 'the-king-james-bible.txt'

def get_words():

    words = []

    with open(filename) as f:

        for line in f:

            fields = re.split("\W+", line)

            for w in fields:

                if w and not w.isdigit():
                    words.append(w)

    return words

words = get_words()

c = collections.Counter(words)
common = c.most_common(10)

for e, i in common:
    print(f'{e}: {i}')

该示例打印了the-king-james-bible.txt文件中的十个最常见的单词。

fields = re.split("\W+", line)

我们将行拆分为单词。\W字符类匹配任何不是单词字符的字符。

for w in fields:

if w and not w.isdigit():
     words.append(w)

我们跳过空字段和诗句符号(它们包含数字)。

c = collections.Counter(words)
common = c.most_common(10)

我们计算出现次数并打印前十个最常用的词。

$ ./word_freq.py 
the: 62103
and: 38848
of: 34478
to: 13400
And: 12846
that: 12576
in: 12331
shall: 9760
he: 9665
unto: 8942

Python字符串分区

partition方法在给定分隔符第一次出现时拆分序列,并返回一个三元组,其中包含分隔符之前的部分、分隔符本身以及分隔符之后的部分。

rpartition方法在给定分隔符的最后一次出现处拆分序列,并返回一个三元组,其中包含分隔符之前的部分、分隔符本身以及分隔符之后的部分。

#!/usr/bin/python

import os 

files = os.listdir('.')

for file in files:
    
    data = file.partition('.')
    print(f'{data[0]} has extension {data[2]}')

该示例列出了当前工作目录并将每个文件切割为其名称和扩展名。它使用分区

$ ./partition.py 
words has extension txt
split_lines2 has extension py
splitting has extension py
split_lines has extension py
word_freq2 has extension py
split_right has extension py
the-king-james-bible has extension txt
reg_split has extension py
word_freq has extension py
partition has extension py
maxsplit has extension py

在本教程中,我们展示了如何在Python中拆分字符串。

阅读Python教程或列出所有Python教程。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏