第一次写这里,不知道如何解决。
基本上我想用多个分隔符分割一个大字符串,分隔符不是逗号、制表符或类似的东西。基本上这个字符串由四位数字分隔,前两个数字描述它有什么类型的数据,最后两个描述数据的长度,所以它是这样的:
PN1121 E 1st St0008纽约0102NY020510003
其中 PN 是地址,11 是地址的字符数,接下来的 00 表示城市,8 是地址的字符数,接下来的 01 表示州,有 2 个字符,依此类推。
我的问题是一种提取这些数据并将其分割成逗号的方法,如下所示:21 E 1st St, New York, NY, 10003。不仅如此,还会有一些字符串不会有的数据,所以它会是这样的:
PN1121 E 第一街0102NY020510003
在这些情况下,应替换为这样的空格:21 E 1st St, , NY, 10003
我一直在为此苦苦挣扎,有人可以帮助我吗?我不会附加该字符串,因为它太长了,但您可以获取如下数据:PN,00,01, ...., 40,41。
我已经在Python中尝试过这个,但我不会撒谎,编程不是我的强项,我只知道一些非常基本的Python。也尝试过聊天 gpt,但它可能适合我。你能用Python教我吗?
欢迎来到 Stackoverflow 社区! 考虑到你只了解一些非常基础的python,我尝试使用简单直接的代码来解决问题。 # 后面是代码的解释。
def delimite(string):
count = 0 # count stands for the delimeters. When count == 4, we get a complete delimeter
length = 0 # length used to store the length of each data
number = "" # number used to store the delimeters
result = ""
for letter in string:
if length == 0: # if length == 0, it means we are in process of extracting the delimeters
count = count + 1
number = number + letter # store the delimeters
if count == 4: # if count == 4, it's time to get a delimeter
length = int(number[2:]) # extract the last two digits
number = "" # empty number and count
count = 0
else: # if length != 0, we are in process of extracting the data
result = result + letter # store the data one by one
length = length - 1
if length == 0: # length == 0 means we finishing storing current data, and we add a ", "
result = result + ", "
result = result.rstrip(", ") # using the rstrip method to remove the last ", "
return result
希望这对您有帮助。如果您有任何疑问,请随时询问。