如何根据一些规则更改字符串?

2024-05-23 18:17:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下文本,每行有两个短语,用"\t"分隔

RoadTunnel    RouteOfTransportation
LaunchPad   Infrastructure
CyclingLeague   SportsLeague
Territory   PopulatedPlace
CurlingLeague   SportsLeague
GatedCommunity  PopulatedPlace

我想得到的是在单独的单词中添加_,结果应该是:

Road_Tunnel    Route_Of_Transportation
Launch_Pad  Infrastructure
Cycling_League  Sports_League
Territory   Populated_Place
Curling_League  Sports_League
Gated_Community Populated_Place

没有像"ABTest""aBTest"这样的案例,也有像三个字在一起"RouteOfTransportation"这样的案例,我尝试了几种方法,但都没有成功。你知道吗

我的一个尝试是:

textProcessed = re.sub(r"([A-Z][a-z]+)(?=([A-Z][a-z]+))", r"\1_", text)

但没有结果


Tags: 文本launchpadplaceinfrastructure案例sportsleagueterritory
3条回答

使用正则表达式和re.sub。你知道吗

>>> import re
>>> s = '''LaunchPad   Infrastructure
... CyclingLeague   SportsLeague
... Territory   PopulatedPlace
... CurlingLeague   SportsLeague
... GatedCommunity  PopulatedPlace'''
>>> subbed = re.sub('([A-Z][a-z]+)([A-Z])', r'\1_\2', s)
>>> print(subbed)
Launch_Pad   Infrastructure
Cycling_League   Sports_League
Territory   Populated_Place
Curling_League   Sports_League
Gated_Community  Populated_Place

编辑:这里还有一个,因为您的测试用例没有足够的内容来确定您到底想要什么:

>>> re.sub('([a-zA-Z])([A-Z])([a-z])', r'\1_\2\3', 'ABThingThing')
'AB_Thing_Thing'

根据您的需要,可以采用以下稍微不同的解决方案:

import re
result = re.sub(r"([a-zA-Z])(?=[A-Z])", r"\1_", s)

它将在紧跟在另一个字母后面的任何大写字母之前插入_(无论是大写还是小写)。你知道吗

  • "TheRabbit IsBlue"=>;"The_Rabbit Is_Blue"
  • "ABThing ThingAB"=>;"A_B_Thing Thing_A_B"

它不支持特殊字符。你知道吗

组合re.findallstr.join

>>> "_".join(re.findall(r"[A-Z]{1}[^A-Z]*", text))

相关问题 更多 >