gpt4 book ai didi

python - 如何在 python 中替换和插入新的子字符串?

转载 作者:行者123 更新时间:2023-12-04 11:44:53 27 4
gpt4 key购买 nike

这是一个有效的代码,用之前修改过的另一个子字符串替换一个子字符串可能不是很有效的代码

输入字符串:

text = ["part1 Pirates (2006)",
"part2 Pirates (2006)"
]

输出字符串:

 Pirates PT1 (2006)

Pirates PT2 (2006)

它必须用'PT'替换'part1''part2等子字符串并将其复制到标题和年份子字符串之间代码:

#'''''''''''''''''''''''''
# are there parenthesis?
#
def parenth(stringa):
count = 0
for i in stringa:
if i == "(":
count += 1
elif i == ")":
count -= 1
if count < 0:
return False
return count == 0


#'''''''''''''''''''''''''
# extract 'year' from
# the string
#
def getYear(stringa):
if parenth(stringa) is True:
return stringa[stringa.find("(")+1:stringa.find(")")]



#Start
for title in text:

#Does the year exist ? try to Get it ---------> '2006'
yearStr = getYear(title)

#Get integer next to 'part' substring -------> '1'
intPartStr = re.findall(r'part(\d+)', title)

#Delete 'part' Substring --------------------> 'Pirates (2006)
partStr = re.sub(r'part(\d+)',"",title)

#Build a new string -------------------------> "PT1 (2006)"
newStr = "PT" + intPartStr[0] + " (" + yearStr + ")"

#Update title with new String newStr --------> "Pirates PT1 (2006)"
result = re.sub(r'\(([0-9]+)\)',newStr,partStr)

#End
print (result)

但是当列表是这样的时候

text = ["pt1 Pirates (2006)",
"part 2 Pirates (2006)"
]

我不知道如何提取“part”、“pt”或“part 2”等旁边的整数

编辑:

我以为这个字符串是相同的,但事实并非如此,对不起

如何解决?

"part 2 the day sports stood still (2021)"

\w+ 没有抓取所有的单词

最佳答案

您可以同时进行所有替换:

import re

text = [
"part1 Pirates (2006)",
"part2 Pirates (2006)",
"pt1 Pirates (2006)",
"part 2 Pirates (2006)",
"part 1 The day sports stood still (2021)"
]

pattern = r'(?:part|pt)\s?(\d+)\s?(\b[\w\s]+\b)\s?\((\d+)\)'
substitute = r'\2 PT\1 (\3)'

for title in text:
title = re.sub(pattern, substitute, title)

# if you want the result in a new array:
text_formatted = [re.sub(pattern, substitute, title) for title in text]

正则表达式解释:

  • (?:part|pt)\s?(\d+) 忽略文本并捕获值(第 1 组)
  • (\b[\w\s]+\b) 捕获标题(第 2 组)
  • \((\d+)\) 在括号中捕获年份(第 3 组)
  • '\2 PT\1 (\3)' 用组号重新创建字符串

关于python - 如何在 python 中替换和插入新的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66933956/

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