【问题标题】:Is there a special way python can split a string without a delimiter, only by the capitals letters? [duplicate]python有没有一种特殊的方式可以分割一个没有分隔符的字符串,只用大写字母? [复制]
【发布时间】:2020-09-15 00:49:35
【问题描述】:

我在一个文本文件中有很多单词,每个单词都没有用任何分隔符分隔,但是我们可以分辨出不同的单词,因为每个单词都以大写字母开头。我想提取所有单词并将它们存储在一个列表中:我的 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']

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

AppleBananaGrapeKiwiRaspberry
PineappleOrangeWatermelonMangoLeecheeCoconutGrapefruit
BlueberryPear
Passionfruit

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

【问题讨论】:

标签: python split delimiter


【解决方案1】:

使用正则表达式:

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

编译正则表达式将在您多次使用它时加快执行速度,即在迭代大量输入行时。

【讨论】:

  • 编译正则表达式将在您多次使用它时加快执行速度,即在迭代大量输入行时。
  • 什么意思?这实际上只是一行代码。编译表达式是可选的,你也可以像re.findall(r'[A-Z][a-z]*', test)一样调用它。
  • 我知道这不是真正的“python 代码”,但是使用正则表达式进行字符串操作和搜索要容易得多,因此 regexen 的基本用法是编码器工具箱中的一项很好的技能。跨度>
【解决方案2】:

从 python 3.6 开始,你可以使用新的 f 字符串

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

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

(抱歉搞砸了删除帖子并犯了很多错误)

【讨论】:

  • 但是正则表达式更快
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 2019-03-19
  • 1970-01-01
  • 2021-02-25
  • 1970-01-01
相关资源
最近更新 更多