簡體   English   中英

python 打開 csv 搜索模式並剝離其他所有內容

[英]python open csv search for pattern and strip everything else

我有一個 csv 文件“svclist.csv”,其中包含一個單列列表,如下所示:

pf=/usr/sap/PL5/SYS/profile/PL5_D00_s4prd1
pf=/usr/sap/PL5/SYS/profile/PL5_ASCS01_s4prdascs

我需要從除 PL5 目錄和最后一個目錄中的 2 個數字之外的所有內容中刪除每一行,並且應該看起來像這樣

PL5,00
PL5,01

我開始的代碼如下:

clean_data = []
with open('svclist.csv', 'rt') as f:
    for line in f:
        if line.__contains__('profile'):
        print(line, end='')

我被困在這里。

在此先感謝您的幫助。

您可以為此使用正則表達式,(通常,在嘗試提取模式時,這可能是一個不錯的選擇)

import re
pattern = r"pf=/usr/sap/PL5/SYS/profile/PL5_.*(\d{2})"

with open('svclist.csv', 'rt') as f:
    for line in f:
        if 'profile' in line:
            last_two_numbers = pattern.findall(line)[0]
            print(f'PL5,{last_two_numbers}')

此代碼遍歷每一行,檢查“profile”是否在該行中(這與 _包含_ 相同),然后根據模式提取最后兩位

您可以使用正則表達式 - (PL5)[^/].{0,}([0-9]{2,2})

為了解釋,只需復制正則表達式並將其粘貼到此處 - 'https://regexr.com'。 這將解釋正則表達式的工作原理,您可以進行所需的更改。

import re
test_string_list = ['pf=/usr/sap/PL5/SYS/profile/PL5_D00_s4prd1',
                    'pf=/usr/sap/PL5/SYS/profile/PL5_ASCS01_s4prdascs']

regex = re.compile("(PL5)[^/].{0,}([0-9]{2,2})")
result = [] 
for test_string in test_string_list:
    matchArray = regex.findall(test_string)
    result.append(matchArray[0])
with open('outfile.txt', 'w') as f:
    for row in result:
        f.write(f'{str(row)[1:-1]}\n')

在上面的代碼中,我創建了一個空列表來保存元組。 然后,我正在寫入文件。 我需要刪除開頭和結尾的 () 。 這可以通過 str(row)[1:-1] 來完成,這將對字符串進行切片。 然后,我使用格式化字符串將內容寫入“outfile.csv”

我假設數字總是在兩個下划線之間。 你可以在你的 for 循環中運行類似的東西。

test_str = "pf=/usr/sap/PL5/SYS/profile/PL5_D00_s4prd1"

test_list = test_str.split("_")  # splits the string at the underscores

output = test_list[1].strip(
    "abcdefghijklmnopqrstuvwxyz" + str.swapcase("abcdefghijklmnopqrstuvwxyz"))  # removing any character

try:
    int(output) # testing if the any special characters are left
    print(f"PL5, {output}")
except ValueError:
    print(f'Something went wrong! Output is PL5,{output}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM