【发布时间】: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 是否有一种特殊的方法可以在没有分隔符的情况下拆分文本,只用大写字母。 如果没有,有人可以告诉我更实用的方法吗?
【问题讨论】:
-
这能回答你的问题吗? Split a string at uppercase letters