我有一個這樣的串列:
ques = ['Normal adult dogs have how many teeth?', 'What is the most common training command taught to dogs?', 'What is this?;{;i1.png;};', 'Which part of cats is as unique as human fingerprints?', 'What is a group of cats called??', 'What is this?;{;i2.png;};']
正如我們所看到的,在 ques[2] 和 ques[5] 末尾有一個遵循特定模式的文本 ;{;*;};
那是存盤在目錄中的 img 檔案的名稱。我想提取那些檔案名,即包含以下內容的串列:
Img_name = ['i1.png','i2.png']
同樣在這樣做之后,我想更新 ques 并從中洗掉模式和 img 檔案名。
uj5u.com熱心網友回復:
使用正則運算式;
import re
image_names = []
pattern = re.compile(r';{;([\w.] );};')
for idx, item in enumerate(ques):
result = re.search(pattern, item)
if result:
image_names.append(result.group(1))
ques[idx] = re.sub(pattern, '', item)
print(ques)
print(image_names)
uj5u.com熱心網友回復:
如果您使用的是 Python 3.8,則可以充分利用walrus 運算子來獲得簡潔的運算式:
pat = re.compile(r';{;(.*?);};')
img_names = [m.group(1) for s in ques if (m := re.search(pat, s))]
ques_clean = [re.sub(pat, '', s) for s in ques]
在您的資料上:
>>> img_name
['i1.png', 'i2.png']
>>> ques_clean
['Normal adult dogs have how many teeth?',
'What is the most common training command taught to dogs?',
'What is this?',
'Which part of cats is as unique as human fingerprints?',
'What is a group of cats called??',
'What is this?']
uj5u.com熱心網友回復:
使用正則運算式替換
import re
# File pattern
file_pattern = re.compile(r"\;{;\w \.\w ;\};") # file name pattern
def replace(m):
' Function to update file and return empty stsring for pattern detected '
files_found.append(m[0])
return ""
ques = ['Normal adult dogs have how many teeth?', 'What is the most common training command taught to dogs?', 'What is this?;{;i1.png;};', 'Which part of cats is as unique as human fingerprints?', 'What is a group of cats called??', 'What is this?;{;i2.png;};']
# Initialize file list to empty list
files_found = []
# Use list comprehension to create list without files and update files found
new_ques = [file_pattern.sub(replace, q) for q in ques]
print(files_found)
print(new_ques)
輸出
[';{;i1.png;};', ';{;i2.png;};']
['Normal adult dogs have how many teeth?', 'What is the most common training command taught to dogs?', 'What is this?', 'Which part of cats is as unique as human fingerprints?', 'What is a group of cats called??', 'What is this?']
???
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448607.html
標籤:Python python-3.x 正则表达式 列表
