我有下面的代码。基本上,我想把像"appleBanana","bananaFruit","cherryBlossom“这样的数组转换成”苹果香蕉“,”香蕉果“,”樱花“。
这是用Python编写的。
可重现的例子:
typelist = ["appleBanana", "bananaFruit", "cherryBlossom"]
typelist2 = ['']
last_was_upper = True
counter = 0
for d in typelist:
for c in d:
if c.isupper():
if not last_was_upper:
typelist2[counter] += ' '
last_was_upper = True
else:
last_was_upper = False
typelist2[counter] += c
counter = counter + 1
print(typelist2)编辑
对于我的实际代码,这是我得到的输出
[' Advanced Algebra', ' Problem Solvingand Data Analysis', ' Basic Algebra', ' Problem Solvingand Data Analysis', ' Advanced Algebra', ' Advanced Algebra', ' Advanced Algebra', ' Problem Solvingand Data Analysis', ' Advanced Algebra', ' Problem Solvingand Data Analysis', ' Problem Solvingand Data Analysis', ' Problem Solvingand Data Analysis', ' Advanced Algebra', ' Problem Solvingand Data Analysis', ' Advanced Algebra', ' Advanced Algebra', ' Advanced Algebra', ' Advanced Algebra', ' Advanced Algebra', ' Problem Solvingand Data Analysis']注意他们中的一些人在短语前有一个空格,而另一些人在字母之间没有空格。我想要的结果是简单的“高级代数”(显然有各自的字段)。如何删除开头的空格,并在中间为所有空格添加空格?
发布于 2020-06-29 04:59:22
您可以在一行解决方案中使用简单的列表理解来实现输出:
import re
typelist=["appleBanana", "bananaFruit", "cherryBlossom"]
typelist2=[re.sub(r"(\w)([A-Z])", r"\1 \2", element).title() for element in typelist]输出:
>>> typelist2
['Apple Banana', 'Banana Fruit', 'Cherry Blossom']re模块包含在标准的python发行版中,需要在大写字母前插入一个空格。
调用title()方法将第一个字母大写。
发布于 2020-06-29 05:02:53
这里有一个没有正则表达式的解决方案(它没有问题,只是采用了不同的方法):
typelist = ["appleBanana", "bananaFruit", "cherryBlossom"]
# for word in typelist
# for letter in word:
# if letter is uppercase, split word by index of letter,
# then uppercase the first letter and put a space between the two words.
fixed_typelist = []
for word in typelist:
for index, letter in enumerate(word):
if letter.isupper():
split_letter = word[:index].title(), word[index:]
fixed_word = ' '.join(split_letter)
fixed_typelist.append(fixed_word)
print(fixed_typelist)
>>> ['Apple Banana', 'Banana Fruit', 'Cherry Blossom']本质上,核心问题是识别大写字母的索引(或位置)。我选择通过enumerate来实现这一点,它返回字母索引和字母本身的迭代量。找到索引后,您只需将单词拆分,并将第一个单词的第一个字母大写。
发布于 2020-06-29 05:12:11
另一个不带正则表达式的版本:
typelist = ["appleBanana", "bananaFruit", "cherryBlossom"]
for s in typelist:
c, c2 = [], []
for ch in s:
if ch.isupper():
c, c2 = c2, c
c.append(ch)
print(''.join(c2).title(), ''.join(c).title())打印:
Apple Banana
Banana Fruit
Cherry Blossom编辑:
typelist = ["appleBanana", "bananaFruit", "cherryBlossom", 'problemSolvingAndDataAnalysis']
out = []
for s in typelist:
words = [[]]
for ch in s:
if ch.isupper():
words.append([])
words[-1].append(ch)
out.append(' '.join(''.join(w).title() for w in words))
print(out)打印:
['Apple Banana', 'Banana Fruit', 'Cherry Blossom', 'Problem Solving And Data Analysis']https://stackoverflow.com/questions/62628038
复制相似问题