【发布时间】:2021-02-24 01:37:14
【问题描述】:
我有一个包含以下标题和(示例)数据的 CSV 文件:
StopName,RouteName,Travel_Direction,Latitude,Longitude
StreetA @ StreetB,1 NameA,DirectionA,Lat,Long
StreetC @ StreetD,1 NameA,DirectionA,Lat,Long
...
StreetE @ StreetF,1 NameA,DirectionB,Lat,Long
StreetG @ StreetH,1 NameA,DirectionB,Lat,Long
...
StreetI @ StreetJ,2 NameB,DirectionC,Lat,Long
StreetK @ StreetL,2 NameB,DirectionC,Lat,Long
...
StreetM @ StreetN,2 NameB,DirectionD,Lat,Long
StreetO @ StreetP,2 NameB,DirectionD,Lat,Long
.
.
.
我想使用正则表达式(目前在 Notepad++ 中)得到以下结果:
1 NameA - DirectionA=[[StreetA @ StreetB,[Lat,Long]], [StreetC @ StreetD,[Lat,Long]], ...]
1 NameA - DirectionB=[[StreetD @ StreetE,[Lat,Long]], [StreetF @ StreetG,[Lat,Long]], ...]
2 NameB - DirectionC=[[StreetH @ StreetI,[Lat,Long]], [StreetJ @ StreetK,[Lat,Long]], ...]
2 NameB - DirectionD=[[StreetL @ StreetM,[Lat,Long]], [StreetN @ StreetO,[Lat,Long]], ...]
.
.
.
使用正则表达式和替换,
RgX: ^([^,]*),([^,]*),([^,]*),(.*)
Sub: $2 - $3=[$1,[\4]]
Demo: https://regex101.com/r/gS9hD6/1
我已经走到这一步了:
1 NameA - DirectionA=[StreetA @ StreetB,[Lat,Long]]
1 NameA - DirectionA=[StreetC @ StreetD,[Lat,Long]]
1 NameA - DirectionB=[StreetE @ StreetF,[Lat,Long]]
1 NameA - DirectionB=[StreetG @ StreetH,[Lat,Long]]
2 NameB - DirectionC=[StreetI @ StreetJ,[Lat,Long]]
2 NameB - DirectionC=[StreetK @ StreetL,[Lat,Long]]
2 NameB - DirectionD=[StreetM @ StreetN,[Lat,Long]]
2 NameB - DirectionD=[StreetO @ StreetP,[Lat,Long]]
在一个新的正则表达式中,我尝试将上述结果拆分为“=”,但不知道从那里去哪里。
我认为获得所需结果的一种方法是保留“=”之前的第一个唯一实例,用“,”替换新行并用 [..] 将其括起来以使其成为数组形式。
编辑: 大约有 10,000 个站点(总共),但只有大约 100 条独特的路线。
编辑 2:(也许我现在要求的更改太多)
对于第一个正则表达式:
- 如果我想使用“\n”而不是“=”怎么办?
在第二次正则表达式替换开始时,
- 如果我只有 RouteName 和 StopName 列,像这样:
1 NameA - DirectionA=[StreetA @ StreetB, ...]? - 同样,如果我只有 RouteName 和 Coordinates,像这样:
1 NameA - DirectionA=[[Lat,Long]]?
【问题讨论】:
-
你不能只用正则表达式做进一步的部分。使用编程语言,它会让你的任务变得很容易。
-
@karthikmanchala 可以用 1 个正则表达式完成,多次应用 :-)
-
@Mariano 不,它不能,如果有动态数量的唯一键。在您的回答中,您假设只有 2 个键.. 可能是 3 个或更多... :) 检查this
-
@karthikmanchala 这就是你必须多次应用的地方(相同的正则表达式),在我的回答中描述为第 3 步。 check this
-
@Mariano 完全正确.. 如果我有 100 次出现怎么办?还是500? 1000?这就是
programming language和easy-to-do发挥作用的地方.. :)