使用您选择的给定分隔符将字符和数字段与给定字符串分隔开



我正在尝试编写一个函数,该函数以两个字符串作为输入,并返回一个包含提取的字符和数字段的元组。类似:

string_to_parse = 'Copenhagen hosted Cop -09 summit at Bella Centre in 2009 , which was attended by delegates from more than 100 countries.'
separator = '_'
tuple_to_be_returned = ('CopenhagenhostedCop_summitatBellaCentrein_whichwasattendedbydelegatesfrommorethan_countries','09 _2009_100')

有人知道我该怎么做吗?任何想法都很棒!提前感谢!

这是一个小而讨厌的、有点像意大利面条的代码,但它是有效的,重构这个函数并使其更整洁将是一个很好的练习。祝你好运

def separate(string, separator):
words = []
nums = []
for word in string.split(" "):
if word.isnumeric():
nums.append(word)
string = string.replace(word, separator, 1)
else:
words.append(word)
return "".join(map(lambda s: s if s.isalpha() or s == separator else "", "".join(string.split(" ")))), separator.join(nums)

此代码适用于我:

import re
def function (strng):
pattern = r'-?(d+)s?,?'
results = re.findall(pattern, strng)
nums = ['_' + vals for vals in results]
nums = ' '.join(nums)


values = r'12'
new =re.sub(pattern, '_', strng)
new = new.split()
return (''.join(new)) , (str(nums))

最新更新