【发布时间】:2022-01-02 19:48:16
【问题描述】:
我有一个独特的用例。我有一个以下格式的 txt 文件,其中每一行都以“APA”开头并以“||”结尾(长度和内容不同,无所谓)
APA lEDGER|5023|124223|STAFF NAME|XYZ|123||
APA lEDGER|5023|124223|STAFF NAME|XYZ|131|12r2gw||
APA lEDGER|5023|124223|STAFF NAME|XYZ|43s|12|123sdfq|prime||
然而,在某些行中,由于未知原因,其中一些行被分割成这样:
APA lEDGER|5023|hello|
40937 / 903.01
for period: 2021|8|332.48||
从技术上讲,这条线应该是这样的:
APA lEDGER|5023|hello|40937 / 903.01 for period: 2021|8|332.48||
文件非常大(16MB),这是我想出的逻辑:
将每一行读入字符串列表并应用以下算法:
pattern = re.compile("\s*[^APA]")
patternOK = re.compile("\s*[APA]")
final_list = [] --list to store the cleaned strings
ptr=0
for elem in string_list:
if(elem.startswith ("APA") and elem.endswith("||")):
final_list.append(elem) --add each string with the proper format to the the final list
--maintain a pointer, point it to the current string and one to the previous string, if the current string does not start with an APA then append all the strings in a while loop and then append it back to the previous proper string
if(ptr<len(string_list)):
if (ptr - 1 >= 0):
prev_el = str(string_list[ptr-1])
curr_el = str(string_list[ptr])
if(pattern.match(curr_el.strip())):
while (pattern.match(string_list[ptr])):
prev_el = prev_el + '|'+string_list[ptr]
ptr = ptr + 1
if(ptr+1 > len(string_list)):
break
final_list.append(prev_el) --append the cleaned string to the final list
ptr = timer+1
大多数情况下,它有效。但是,我可以看到一些结果被省略或不按插入顺序。请随意提供您自己的逻辑。
总之,我需要一个具有上述正确格式的字符串列表。
谢谢
【问题讨论】:
-
第 3 行包含两个 '||'像这样:“123sdfq||素数||”是错字吗?
-
是的,这是一个错字。好电话
标签: python python-3.x string list dataframe