有没有一种特殊的方法 python 可以在没有分隔符的情况下仅通过大写字母来拆分字符串?
Is there a special way python can split a string without a delimiter, only by the capitals letters?
我在一个文本文件中有很多单词,每个单词没有任何分隔符分隔,但我们可以区分不同的单词,因为每个单词都以大写字母开头。我想提取所有单词并将它们存储在列表中:我的 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 可以在没有定界符的情况下仅按大写字母拆分文本。
如果没有,谁能告诉我更实用的方法?
使用正则表达式:
import re
test = 'HelloWorldExample'
r_capital = re.compile(r'[A-Z][a-z]*')
r_capital.findall(test) # ['Hello', 'World', 'Example']
编译正则表达式将在多次使用时加快执行速度,即迭代大量输入行时。
使用自 python 3.6 以来的新 f 弦,您可以使用
words = "".join([f" {s}" if s.isupper() else s for s in yorufile.read() if s.strip()]).split(" ")[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']
里面words.txt (注意有换行,这只是实际文本的一个例子):
AppleBananaGrapeKiwiRaspberry
PineappleOrangeWatermelonMangoLeecheeCoconutGrapefruit
BlueberryPear
Passionfruit
我的代码工作正常,但我想知道是否有一种特殊的方法 python 可以在没有定界符的情况下仅按大写字母拆分文本。 如果没有,谁能告诉我更实用的方法?
使用正则表达式:
import re
test = 'HelloWorldExample'
r_capital = re.compile(r'[A-Z][a-z]*')
r_capital.findall(test) # ['Hello', 'World', 'Example']
编译正则表达式将在多次使用时加快执行速度,即迭代大量输入行时。
使用自 python 3.6 以来的新 f 弦,您可以使用
words = "".join([f" {s}" if s.isupper() else s for s in yorufile.read() if s.strip()]).split(" ")[1:]
这是我尝试的最终版本,但随着我的继续,它变得越来越丑陋。
(抱歉乱删帖,犯了很多错误)