python有没有一种特殊的方法,可以把一个字符串拆分,不用定界符,只用大写字母来拆分?[重复]

问题描述 投票:0回答:1

我在一个文本文件中有很多单词,每个单词之间没有任何分隔符,但我们可以分辨出不同的单词,因为每个单词都以大写字母开头。我想把所有的单词提取出来并存储在一个列表中。我的python脚本:

words = ''
with open("words.txt",'r') as mess:
    for l in mess.read():
        if l.isupper():
            words += ','+l
        else:
            words += l
words = [word.strip() for word in words.split(',') if word]
print(words)

输出:

['Apple', 'Banana', 'Grape', 'Kiwi', 'Raspberry', 'Pineapple', 'Orange', 'Watermelon', 'Mango', 'Leechee', 'Coconut', 'Grapefruit', 'Blueberry', 'Pear', 'Passionfruit']

Inside words. txt (注意,有换行,这只是实际文本的一个例子):

AppleBananaGrapeKiwiRaspberry
PineappleOrangeWatermelonMangoLeecheeCoconutGrapefruit
BlueberryPear
Passionfruit

我的代码工作正常,但我想知道是否有一种特殊的方法python可以在没有定界符的情况下分割文本,只用大写字母分割.如果没有,谁能告诉我更实用的方法?

python opencv split delimiter
1个回答
3
投票

使用正则表达式。

import re
test = 'HelloWorldExample'
r_capital = re.compile(r'[A-Z][a-z]*')
r_capital.findall(test) # ['Hello', 'World', 'Example']

当你多次使用正则表达式时,编译正则表达式会加快执行速度,也就是说,当你遍历大量的输入行时。


1
投票

在python 3.6之后,新的f-strings中,你可以使用

words = "".join([f" {s}" if s.isupper() else s for s in yorufile.read() if s.strip()]).split(" ")[1:]

这是我尝试的最终版本,但随着我的继续,它变得越来越丑陋。

(对不起,我乱删帖,犯了大量的错误)

© www.soinside.com 2019 - 2024. All rights reserved.