gpt4 book ai didi

python - 如何正确加入尾随或破折号开头的单词? - Python

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:37 24 4
gpt4 key购买 nike

我有一个字符串列表,其中包含以 - 结尾或开头的标记,我需要将它们连接起来,以便带破折号的单词连接成正确的标记,例如

[输入]:

x = "ko- zo- fond- w- a (* nga- bantawana )."
y = "ngi -leth- el a -unfundi"
z = "ba- ya -gula buye incdai- fv -buye"

[输出]:

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

最佳答案

x = "ko- zo- fond- w- a (* nga- bantawana )." #or any other input 
x = x.replace("- ", "").replace(" -", "")

它将从输入中删除所有出现的“-”和“-”,根据需要有效地转换字符串。

关于python - 如何正确加入尾随或破折号开头的单词? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20494512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com