如何正确加入破折号或破折号的单词? - 蟒蛇

 村头的小路_157 发布于 2023-02-11 18:22

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

[在]:

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(" -", "")

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

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有