我有一个字符串列表,其中包含结束或开始的标记-
我需要将它们连接起来,以便带有破折号的单词连接到正确的标记,例如
[在]:
x = "ko- zo- fond- w- a (* nga- bantawana )." y = "ngi -leth- el a -unfundi" z = "ba- ya -gula buye incdai- fv -buye"
[OUT]:
kozofondwa (* ngabantawana ). ngilethel aunfundi bayagula buye incdaifvbuye
我一直在这样做,它真的很丑陋而且不优雅,特别是当我需要两次调用该函数时.还有其他方法可以实现相同的输出吗?可能与正则表达式或其他什么?
x = "ko- zo- fond- w- a (* nga- bantawana )." y = "ngi -leth- el a -unfundi" z = "ba- ya -gula buye incdai- fv -buye" def join_morph(text): tempstr = "" outstr = [] for i in text.split(): if i.startswith('-'): outstr[len(outstr)-1]+=i elif i.endswith('-'): tempstr+=i else: tempstr+=i outstr.append(tempstr) tempstr = "" return " ".join(outstr) # There is a problem because of the ordering of # the if-else, it can only handle head or # trailing dashes, not both a = join_morph(x) print a a = join_morph(x).replace('-','') print a a = join_morph(join_morph(y)).replace('-','') print a a = join_morph(join_morph(z)).replace('-','') print a
Saša Šijak.. 5
x = "ko- zo- fond- w- a (* nga- bantawana )." #or any other input x = x.replace("- ", "").replace(" -", "")
它将从输入中删除所有出现的" - "和" - ",从而根据需要有效地转换字符串.